【问题标题】:Why is lxml not finding this class?为什么 lxml 找不到这个类?
【发布时间】:2013-09-08 16:37:37
【问题描述】:

我正在尝试使用 Python 从页面中抓取一些文本。应该很容易,但lxml 似乎总是让我感到惊讶。这是我尝试过的:

>>> import lxml.html
>>> import urllib

>>> response = urllib.urlopen('http://www.codecademy.com/username')
>>> tree = lxml.html.parse(response)
>>> root = tree.getroot()
>>> root.find_class('stat-count')
[]

我很困惑。以下是在 html 中:<span class="stat-count">27</span>(同一个类有第二个跨度。)我无法想象为什么 find_class 方法对某些元素会以这种方式工作,而对其他元素则不行。

我愿意采取任何策略来获取这些span 标记中的第一个的内容。但我真的很想深入了解这样做的正确方法。我想使用lxml 会比使用正则表达式更快且更易于维护,但我似乎从来没有很好的体验。

【问题讨论】:

  • 事实证明这段代码没有问题,但是由于某种原因,特定的用户名重定向到了登录页面。

标签: python css web-scraping lxml


【解决方案1】:

它应该可以工作,提供root = tree.getroot()

import lxml.html
import urllib

response = urllib.urlopen('http://www.codecademy.com/username')
tree = lxml.html.parse(response)
# tree.write('/tmp/test.html')
root = tree.getroot()
print(root.find_class('stat-count'))

产量

[<Element span at 0xa3146bc>, <Element span at 0xa3146ec>]

【讨论】:

  • 我放弃了。现在我无法重现失败的行为。
【解决方案2】:

你应该试一试beautifulsoup

import urllib
from bs4 import BeautifulSoup as BS

response = urllib.urlopen('http://www.codecademy.com/username').read()
soup = BS(response)
points = soup.find("span",{"class":"stat-count"}).get_text()
print points

对于给定的 url,它会打印 0,但是当我使用我的 codeacademy 用户名时,它会返回 90,所以它工作正常

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-26
    • 2015-04-11
    • 2011-09-06
    • 2022-01-05
    • 2011-08-03
    • 2020-05-26
    • 2014-01-05
    • 2015-06-22
    相关资源
    最近更新 更多