2017-01-03 22 views
0

私はPythonには初めてです。これはBeautifulsoupでの私の最初の練習用コードです。私はまだ特定のデータ抽出の問題に対する創造的な解決法を学んだことはありません。CSVテキスト抽出Beautifulsoup

このプログラムはうまく印刷されますが、CSVに抽出するのは困難です。それは最初の要素を取りますが、他のすべての要素は後ろに残します。空白、区切り文字、または初期テキストの後でコードの抽出を停止させる何かがあるかもしれないと推測できるだけですか?

私はCSV抽出を行ごとに各アイテムに発生させようとしていましたが、明らかにうんざりしていました。助けて頂ける、ありがとうございます。ここで

from urllib.request import urlopen 
from bs4 import BeautifulSoup 
import csv 

price_page = 'http://www.harryrosen.com/footwear/c/boots' 
page = urlopen(price_page) 
soup = BeautifulSoup(page, 'html.parser') 
product_data = soup.findAll('ul', attrs={'class': 'productInfo'}) 

for item in product_data: 

    brand_name=item.contents[1].text.strip() 
    shoe_type=item.contents[3].text.strip() 
    shoe_price = item.contents[5].text.strip() 
    print (brand_name) 
    print (shoe_type) 
    print (shoe_price) 

with open('shoeprice.csv', 'w') as shoe_prices: 
writer = csv.writer(shoe_prices) 
writer.writerow([brand_name, shoe_type, shoe_price]) 
+0

あなたはインデントに問題があります –

答えて

1

は問題にアプローチする一つの方法です:

実装:

data = [{ 
    'brand': item.li.get_text(strip=True), 
    'type': item('li')[1].get_text(strip=True), 
    'price': item.find('li', class_='price').get_text(strip=True) 
} for item in product_data] 

with open('shoeprice.csv', 'w') as f: 
    writer = csv.DictWriter(f, fieldnames=['brand', 'type', 'price']) 
    writer.writerows(data) 

また、CSVヘッダーを書きたい場合は、writer.writerows(data)の前にwriter.writeheader()コールを追加します。

普通のcsv.writerとリスト(またはタプル)のリストを使用することもできますが、この場合はExplositnessと辞書の読みやすさが好きです。

ループで使用されているロケータが改善されていることにも注意してください。.contentsリストを使用して製品の子どもをインデックスで取得するのは良いと思います。

+0

ソリューションありがとうございました! .contentの使用についてのご意見をお待ちしており、データの書式設定についてもっと学びます。 – Splaning

1
with open('shoeprice.csv', 'w') as shoe_prices: 
    writer = csv.writer(shoe_prices) 
    for item in product_data: 
     brand_name=item.contents[1].text.strip() 
     shoe_type=item.contents[3].text.strip() 
     shoe_price = item.contents[5].text.strip() 
     print (brand_name, shoe_type, shoe_price, spe='\n') 

     writer.writerow([brand_name, shoe_type, shoe_price]) 

開いているファイルを外側のループに変更するので、各ループを開く必要はありません。

+1

助けてくれてありがとう宏杰李!これは、知るのに非常に便利な別の方法です。 – Splaning

関連する問題