在html页面上的不同类下打印数据的问题,一起使用美丽的汤

时间:2012-12-19 11:57:32

标签: python-2.7 web-scraping beautifulsoup

我需要从网站上搜索设备的价格,价格在网站上提到两种类型:

  1. 单一价格例如$ 99.99
  2. 价格范围例如。 “49.99美元”到“99.99美元”
  3. 在单个类下提到单个价格值,我可以提取这些值,但在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()
    

    在输出中,我没有得到价格范围的值,我需要的是所有价格的列表。

1 个答案:

答案 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价格。