【发布时间】:2012-12-13 14:26:51
【问题描述】:
我正在尝试从网站上抓取 41 件商品及其价格的清单。但是我的输出 csv 缺少页面末尾的一些 2-3 项。原因是,某些设备的价格与其他设备不同。 我的代码中的递归是针对名称和价格一起运行的,对于在不同类别下提到价格的项目,它从下一个设备中获取价格值。因此,它会跳过最后 2-3 项,因为这些设备的价格已经在以前的设备中以递归方式输入。 以下是参考代码:
# -*- coding: cp1252 -*-
import csv
import urllib2
import sys
import time
from bs4 import BeautifulSoup
page = urllib2.urlopen('http://www.att.com/shop/wireless/devices/smartphones.deviceListGridView.xhr.flowtype-NEW.deviceGroupType-Cellphone.paymentType-postpaid.packageType-undefined.html?taxoStyle=SMARTPHONES&showMoreListSize=1000').read()
soup = BeautifulSoup(page)
soup.prettify()
with open('AT&T_2012-12-28.csv', 'wb') as csvfile:
spamwriter = csv.writer(csvfile, delimiter=',')
spamwriter.writerow(["Date","Month","Day of Week","Device Name","Price"])
items = soup.findAll('a', {"class": "clickStreamSingleItem"},text=True)
prices = soup.findAll('div', {"class": "listGrid-price"})
for item, price in zip(items, prices):
textcontent = u' '.join(price.stripped_strings)
if textcontent:
spamwriter.writerow([time.strftime("%Y-%m-%d"),time.strftime("%B"),time.strftime("%A") ,unicode(item.string).encode('utf8').replace('™','').replace('®','').strip(),textcontent])
价格通常在listGrid-price 下提及,但对于目前价格低于listGrid-price-outOfStock 的某些 2-3 件商品,我需要在递归中也包含此价格,以便正确的价格出现在商品和循环运行之前适用于所有设备。
由于我是编程新手,请原谅我的无知
【问题讨论】:
标签: python-2.7 screen-scraping beautifulsoup