BeautifulSoup - lxml和html5lib解析器刮取差异

时间:2014-03-27 19:08:50

标签: python web-scraping beautifulsoup lxml html5lib

我正在使用 BeautifulSoup 4 Python 2.7 。我想从网站中提取某些元素(数量,请参见下面的示例)。出于某种原因, lxml 解析器不允许我从页面中提取所有所需的元素。它只打印前三个元素。我正在尝试使用 html5lib 解析器来查看是否可以提取所有这些解析器。

该页面包含多个商品及其价格和数量。包含每个项目所需信息的代码的一部分如下所示:

<td class="size-price last first" colspan="4">
                    <span>453 grams </span>
            <span> <span class="strike">$619.06</span> <span class="price">$523.91</span>
                    </span>
                </td>

让我们考虑以下三种情况:

案例1 - 数据:

#! /usr/bin/python
from bs4 import BeautifulSoup
data = """
<td class="size-price last first" colspan="4">
                    <span>453 grams </span>
            <span> <span class="strike">$619.06</span> <span class="price">$523.91</span>
                    </span>
                </td>"""                
soup = BeautifulSoup(data)
print soup.td.span.text

打印:

453 grams 

案例2 - LXML:

#! /usr/bin/python
from bs4 import BeautifulSoup
from urllib import urlopen
webpage = urlopen('The URL goes here')
soup=BeautifulSoup(webpage, "lxml")
print soup.find('td', {'class': 'size-price'}).span.text

打印:

453 grams

案例3 - HTML5LIB:

#! /usr/bin/python
from bs4 import BeautifulSoup
from urllib import urlopen
webpage = urlopen('The URL goes here')
soup=BeautifulSoup(webpage, "html5lib")
print soup.find('td', {'class': 'size-price'}).span.text

我收到以下错误:

Traceback (most recent call last):
  File "C:\Users\Dom\Python-Code\src\Testing-Code.py", line 6, in <module>
    print soup.find('td', {'class': 'size-price'}).span.text
AttributeError: 'NoneType' object has no attribute 'span'

为了使用html5lib解析器提取我想要的信息,我如何调整代码?如果我只是在使用html5lib后在控制台中打印汤,我可以看到所有想要的信息,所以我想它可以让我得到我想要的东西。对于lxml解析器不是这样的,所以我也很好奇lxml解析器似乎使用lxml解析器提取所有数量的事实,如果我使用:

print [td.span.text for td in soup.find_all('td', {'class': 'size-price'})]

2 个答案:

答案 0 :(得分:1)

from lxml import etree

html = 'your html'
tree = etree.HTML(html)
tds = tree.xpath('.//td[@class="size-price last first"]')
for td in tds:
    price = td.xpath('.//span[@class="price"]')[0].text
    strike = td.xpath('.//span[@class="strike"]')[0].text
    spans = td.xpath('.//span')
    quantity = [i.text for i in spans if 'grams' in i.text][0].strip(' ')

答案 1 :(得分:0)

尝试以下方法:

    from bs4 import BeautifulSoup
    data = """
    <td class="size-price last first" colspan="4">
                <span>453 grams </span>
        <span> <span class="strike">$619.06</span> <span 
    class="price">$523.91</span>
                </span>
            </td>"""                
    soup = BeautifulSoup(data)
    text = soup.get_text(strip=True)
    print text