【问题标题】:Not getting any output nor any error for the following code?以下代码没有得到任何输出或任何错误?
【发布时间】:2012-12-12 00:46:21
【问题描述】:

我使用以下代码从 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])

【问题讨论】:

  • 顺便说一句,soup.prettify() 用于输出可读的 HTML,但您不使用该输出。使用时,该行不任何事情。
  • 不,我没有创建任何重复的帐户,user1915050 是我的朋友,他正在和我一起做同一个项目。
  • Okidoki;编码风格有点熟悉。 :-)

标签: python-2.7 screen-scraping beautifulsoup


【解决方案1】:

该页面上没有<div class="top"> 元素带有文本,因此items 是一个空列表。删除text=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')])

【讨论】:

  • 感谢您的回答。我在进行更改后运行了代码,但“项目”对所有行都没有显示!
  • @ChandanKumar:我事先用你的 URL 测试了代码。你确定你做了正确的改变吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多