【发布时间】:2013-08-30 14:30:59
【问题描述】:
在解析 http://en.wikipedia.org/wiki/Israel 时,我遇到了一个带有文本的 H2 标签,但 Beautiful Soup 为它返回了一个 None 类型:
$ python
Python 2.7.3 (default, Apr 10 2013, 05:13:16)
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import bs4
>>> import requests
>>> from pprint import pprint
>>> response = requests.get('http://en.wikipedia.org/wiki/Israel')
>>> soup = bs4.BeautifulSoup(response.content)
>>> for h in soup.find_all('h2'):
... pprint(str(type(h)))
... pprint(h)
... pprint(str(type(h.string)))
... pprint(h.string)
... print('--')
...
"<class 'bs4.element.Tag'>"
<h2>Contents</h2>
"<class 'bs4.element.NavigableString'>"
u'Contents'
--
"<class 'bs4.element.Tag'>"
<h2><span class="mw-headline" id="Etymology"><span id="Etymology"></span> Etymology</span></h2>
"<type 'NoneType'>"
None
--
"<class 'bs4.element.Tag'>"
<h2><span class="mw-headline" id="History">History</span></h2>
"<class 'bs4.element.NavigableString'>"
u'History'
--
请注意,这不是解析问题,Beautiful Soup 可以很好地解析文档。为什么第二个 H2 元素返回 None 类型?是否由于字符串中的前导“”(空格)?我该如何解决这个问题?这是 Python 2.7 上的 Beautiful Soup 4,Kubuntu Linux 12.10。
【问题讨论】:
-
在第 2 个 H2 上有 2 个跨度,其中一个空的跨度为 id ethymology。这可能是 bsoup 失败。
-
我确实注意到了。我该如何围绕它编写代码?
-
为了能够帮助您,我需要深入了解文档,因为我从不使用 bs4 - 如果您不着急,我可以尝试。
标签: python html-parsing beautifulsoup