BeautifulSoup无法找到标签

3

我正在尝试爬取这个页面以及类似此页面的所有页面。我一直在使用BeautifulSoup(也尝试过lxml,但安装存在问题)。我正在使用以下代码:

value = "http://www.presidency.ucsb.edu/ws/index.php?pid=99556"
desiredTag = "span"
r = urllib2.urlopen(value)
data = BeautifulSoup(r.read(), 'html5lib') 
displayText = data.find_all(desiredTag)
print displayText
displayText = " ".join(str(displayText))
displayText = BeautifulSoup(displayText, 'html5lib')

由于某些原因,这并没有拉回 <span class="displaytext">,我也尝试将desiredTag设为p
我是否漏掉了什么?
1个回答

3
你肯定会体验到使用不同解析器(介绍)所带来的差异,BeautifulSoup 中的 html.parserlxml 对我而言都可以使用:
data = BeautifulSoup(urllib2.urlopen(value), 'html.parser') 

证明:

>>> import urllib2
>>> from bs4 import BeautifulSoup
>>> 
>>> url = "http://www.presidency.ucsb.edu/ws/index.php?pid=99556"
>>> 
>>> data = BeautifulSoup(urllib2.urlopen(url), 'html.parser')
>>> data.find("span", class_="displaytext").text
u'PARTICIPANTS:Former Speaker of the House Newt Gingrich (GA);
...

这是一个非常好的、清晰而详尽的回答。我在四处查看时看到了这个,但是在该网站上使用完全相同的代码时,我遇到了“HTMLParser.HTMLParseError:Malformed start tag,在第1183行第15列”。我安装的东西可能有错误吗? - ford prefect
@inquisitiveIdiot 好的,快速检查一下:你正在使用哪个Python版本?谢谢。 - alecxe
2.7.2来自Active Python。这是一个Anaconda安装。 - ford prefect
@inquisitiveIdiot 如果这不是什么大问题,你能否尝试升级至2.7.6或更高版本(2.7.9更好)? - alecxe
为了以后的参考,我相信 Python 的升级非常重要。 - ford prefect

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接