我需要从网站上搜索设备的价格,价格在网站上提到两种类型:
在单个类下提到单个价格值,我可以提取这些值,但在2个类中提到了价格范围。
<div class="gridPrice">"$199.99"
<span class="multiDevicePrice-to">to</span> "$399.99"
作为范围提到的价格是双引号,而单个价格的价格没有任何报价。
我使用以下代码:
import csv
import urllib2
import sys
from bs4 import BeautifulSoup
page = urllib2.urlopen('http://www.att.com/shop/wireless/devices/smartphones.html').read()
soup = BeautifulSoup(page)
soup.prettify()
for anchor1 in soup.findAll('div', {"class": "listGrid-price"},text=True):
if anchor1.string:
print unicode(anchor1.string).strip()
for anchor2 in soup.findAll('div', {"class": "gridPrice"},text=True):
if anchor2.string:
print unicode(anchor2.string).strip()
在输出中,我没有得到价格范围的值,我需要的是所有价格的列表。
答案 0 :(得分:1)
您可以使用.stripped_strings
attribute获取给定标记中所有(已剥离)文本值的可迭代内容:
for anchor1 in soup.findAll('div', {"class": "listGrid-price"}):
textcontent = u' '.join(anchor1.stripped_strings)
if textcontent:
print textcontent
您可能只需选择其中的一个或两个值; itertools.islice
可以提供帮助:
from itertools import islice
for anchor1 in soup.findAll('div', {"class": "listGrid-price"}):
textcontent = u' '.join(islice(anchor1.stripped_strings, 0, 3, 2))
if textcontent:
print textcontent
islice
调用仅选择第一个和第三个元素,即网格中的from和to价格。