0

次のコードを使用して、url からデータをスクレイピングしました (コードに記載されています)。コードを実行しましたが、出力もエラーもスローされませんか? 私はPython言語が初めてなので、ばかげた問題かもしれません。誰かが私を助けることができますか?

import csv
import urllib2
import sys
import time
from bs4 import BeautifulSoup
page = urllib2.urlopen('http://www.t-mobile.de/smartphones/0,22727,23392-_3-0--0-all-,00.html').read()
soup = BeautifulSoup(page)
soup.prettify()
with open('TMO_DE_2012-12-26.csv', 'wb') as csvfile:
    spamwriter = csv.writer(csvfile, delimiter=',')
    spamwriter.writerow(["Date","Month","Day of Week","Device Name","Price"])
    items = soup.findAll('div', {"class": "top"},text=True)
    prices = soup.findAll('strong', {"class": "preis-block"})
    for item, price in zip(items, prices):
        textcontent = u' '.join(price.stripped_strings)
        print unicode(item.string).encode('utf8').strip()
        if textcontent:            
            spamwriter.writerow([time.strftime("%Y-%m-%d"),time.strftime("%B"),time.strftime("%A") ,unicode(item.string).encode('utf8').strip(),textcontent])
4

1 に答える 1

1

そのページにはテキスト<div class="top">を含む要素がないため、空のリストです。フィルターを削除します。itemstext=True

items = soup.findAll('div', {"class": "top"})

そこからすべてのテキストを抽出します。

item_text = u' '.join(item.stripped_strings)
if textcontent and item_text:            
    spamwriter.writerow([time.strftime("%Y-%m-%d"),time.strftime("%B"),time.strftime("%A") , item_text, textcontent])

または、既存のコードに統合します。

with open('TMO_DE_2012-12-26.csv', 'wb') as csvfile:
    spamwriter = csv.writer(csvfile, delimiter=',')
    spamwriter.writerow(["Date","Month","Day of Week","Device Name","Price"])
    items = soup.findAll('div', {"class": "top"})
    prices = soup.findAll('strong', {"class": "preis-block"})
    for item, price in zip(items, prices):
        textcontent = u' '.join(price.stripped_strings)
        item_text = u' '.join(item.stripped_strings)
        if item_text and textcontent:            
            spamwriter.writerow([time.strftime("%Y-%m-%d"),time.strftime("%B"),time.strftime("%A"), item_text.encode('utf8'),textcontent.encode('utf8')])
于 2012-12-26T13:06:01.663 に答える