當解析http://en.wikipedia.org/wiki/Israel
我遇到一個H2
標籤,該標籤具有文本,但美麗的湯返回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'
--
請注意,這不是一個解析的問題,美麗的湯解析文件很好。爲什麼第二個H2
元素返回None
類型?是否由於字符串中的前導「」(空格)?我該如何解決這個問題?這是在Python 2.7上的Beautiful Soup 4,Kubuntu Linux 12.10。
二號H2有2跨度空單用id ethymology。可能bsoup失敗這一個。 – 2013-08-30 14:35:49
我也注意到這一點。怎麼可能我圍繞它編碼? – dotancohen
能夠幫助你我需要挖掘文檔,因爲我從不使用bs4 - 如果你不急,我可以嘗試。 – 2013-08-30 14:40:37