【问题标题】:Issue in scraping data from a html page using beautiful soup使用漂亮的汤从 html 页面中抓取数据的问题
【发布时间】:2012-12-08 19:26:43
【问题描述】:

我正在从网站上抓取一些数据,我可以使用以下引用的代码来做到这一点:

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>

我现在得到的结果显示 None 用于第二个 html 结构,而不是 Free on all dutys,还显示价格值 Free on all关税 strong> 在第二个结构的双引号下被提及,而它在第一个结构的任何引号之外

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

【问题讨论】:

    标签: csv python-2.7 beautifulsoup


    【解决方案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 文件。请注意,我通过简单的替换调用删除了 " 引号。

    【讨论】:

    • 我在运行这个时遇到了这个错误SyntaxError for "else"。
    • @user1915050:你是说SyntaxError吗?我测试了代码,它对我有用,检查你没有忘记它之前的行上的右括号或类似的错误。
    • 运行代码“There is a error in your program, Invalid Syntax”后出现提示,并在代码中突出显示“else”
    • @user1915050:仔细检查你之前没有错过)。在圆括号和方括号内,允许换行,因此 Python 会查看下一行。 else: 在函数调用中没有意义,因此它会为该行引发语法错误,但真正的问题出在前一行。
    • 如果我只想获得“所有关税免费”部分而不是整体“所有关税最多 7 天免费送货”怎么办?
    猜你喜欢
    • 1970-01-01
    • 2021-11-27
    • 2017-08-29
    • 2012-12-13
    • 2012-12-16
    • 1970-01-01
    • 1970-01-01
    • 2012-08-01
    • 1970-01-01
    相关资源
    最近更新 更多