使用漂亮的汤从HTML页面中抓取数据的问题

时间:2012-12-21 08:01:09

标签: csv python-2.7 beautifulsoup

我正在从网站上抓取一些数据,我可以使用下面提到的代码:

import csv
import urllib2
import sys
import time
from bs4 import BeautifulSoup
from itertools import islice
page = urllib2.urlopen('http://shop.o2.co.uk/mobile_phones/Pay_Monthly/smartphone/all_brands').read()
soup = BeautifulSoup(page)
soup.prettify()
with open('O2_2012-12-21.csv', 'wb') as csvfile:
    spamwriter = csv.writer(csvfile, delimiter=',')
    spamwriter.writerow(["Date","Month","Day of Week","OEM","Device Name","Price"])
    oems = soup.findAll('span', {"class": "wwFix_h2"},text=True)
    items = soup.findAll('div',{"class":"title"})
    prices = soup.findAll('span', {"class": "handset"})
    for oem, item, price in zip(oems, items, prices):
            textcontent = u' '.join(islice(item.stripped_strings, 1, 2, 1))
            if textcontent:
                    spamwriter.writerow([time.strftime("%Y-%m-%d"),time.strftime("%B"),time.strftime("%A") ,unicode(oem.string).encode('utf8').strip(),textcontent,unicode(price.string).encode('utf8').strip()])

现在,问题是我正在抓取的所有价格值中的2个具有不同的html结构,然后是其余的值。我的输出csv因为这个而显示“无”值。网页价格的普通html结构是 <span class="handset"> FREE to £79.99</span>

对于那些2个值的结构是 <span class="handset"> <span class="delivery_amber">Up to 7 days delivery</span> <br>"FREE on all tariffs"</span>

我现在正在显示第二个html结构的,而不是所有关税免费,价格值所有关税免费在第二个结构中的双引号下提到,而它在第一个结构中的任何引号之外

请帮我解决这个问题,原谅我的无知,因为我是编程新手。

1 个答案:

答案 0 :(得分:1)

只需使用额外的if声明检测这两个项目:

if price.string is None:
    price_text = u' '.join(price.stripped_strings).replace('"', '').encode('utf8')
else:
    price_text = unicode(price.string).strip().encode('utf8')

然后使用price_text作为CSV文件。请注意,我使用简单的替换调用删除了"引号。