Beautifulsoup soup.body 返回 None
是什么原因导致beautifulsoup在返回soup.body
时显示为None
,而soup.title
却能返回预期的结果呢?
这是我正在解析的页面链接:http://goo.gl/6T3RKV
print(soup.prettify())
这段代码会给出页面的确切HTML内容
1 个回答
4
这是因为 BeautifulSoup 的解析器之间存在差异:
>>> from urllib2 import urlopen
>>> from bs4 import BeautifulSoup
>>> url = 'http://www.emploi.ma/offre-emploi-maroc/commerciaux-en-emission-appels-1019077'
>>> soup = BeautifulSoup(urlopen(url), "html5lib")
>>> print soup.body
None
>>> soup = BeautifulSoup(urlopen(url), "html.parser")
>>> print soup.body
<body class="not-front not-logged-in page-node node-type-offre no-sidebars candidate-context full-node layout-main-last sidebars-split font-size-12 grid-type-960 grid-width-16 role-other" id="pid-node-1019077">
<div class="page" id="page">
...
>>> soup = BeautifulSoup(urlopen(url), "lxml")
>>> print soup.body
<body class="not-front not-logged-in page-node node-type-offre no-sidebars candidate-context full-node layout-main-last sidebars-split font-size-12 grid-type-960 grid-width-16 role-other" id="pid-node-1019077">
<div class="page" id="page">
...
正如你所看到的,html5lib
无法从这个特定的 HTML 中获取 body
。而且,根据 文档,如果没有安装 lxml
,html5lib
会被默认选择:
如果你不指定任何解析器,你将得到安装的最佳 HTML 解析器。Beautiful Soup 将
lxml
的解析器评为最佳,其次是html5lib
,然后是 Python 内置的解析器。