如何摆脱BeautifulSoup用户警告?

jel*_*ang 41 python beautifulsoup user-warning

安装BeautifulSoup之后,每当我在cmd中运行我的Python时,就会出现这个警告.

D:\Application\python\lib\site-packages\beautifulsoup4-4.4.1-py3.4.egg\bs4\__init__.py:166:
UserWarning: No parser was explicitly specified, so I'm using the best
available HTML parser for this system ("html.parser"). This usually isn't a
problem, but if you run this code on another system, or in a different
virtual environment, it may use a different parser and behave differently.

To get rid of this warning, change this:

 BeautifulSoup([your markup])

to this:

 BeautifulSoup([your markup], "html.parser")
Run Code Online (Sandbox Code Playgroud)

我没有理解为什么它出来以及如何解决它.

Eth*_*ein 77

错误消息中明确说明了您的问题的解决方案.像下面这样的代码没有指定XML/HTML/etc. 解析器.

BeautifulSoup( ... )
Run Code Online (Sandbox Code Playgroud)

为了修复错误,您需要指定要使用的解析器,如下所示:

BeautifulSoup( ..., "html.parser" )
Run Code Online (Sandbox Code Playgroud)

如果您愿意,也可以安装第三方解析器.

  • 请参阅 Beautiful Soup 的 [安装解析器](https://www.crummy.com/software/BeautifulSoup/bs4/doc/#installing-a-parser) 文档,了解一些常见解析器(html.parser、lxml)的优点/缺点、html5lib) (2认同)

Gay*_*tti 13

文档建议您安装和使用lxml以提高速度.

BeautifulSoup(html, "lxml")
Run Code Online (Sandbox Code Playgroud)

如果您使用的是早于2.7.3的Python 2版本,或者早于3.2.2的Python 3版本,则必须安装lxml或html5lib-Python的内置HTML解析器在旧版本中不是很好版本.

安装LXML解析器


buf*_*ufh 13

在我看来,之前的帖子并没有回答这个问题。

\n

是的,正如大家所说,您可以通过指定解析器来删除警告。\n正如文档所指出的,这是性能1和一致性2
的最佳实践。

\n

但在某些情况下,您希望消除警告......因此这篇文章。

\n\n

  • 谢谢你!有时图书馆会发出垃圾邮件警告,过滤它就是解决方案 (2认同)

Wil*_* Wu 6

对于 HTML 解析器,您需要安装 html5lib,运行:

pip install html5lib
Run Code Online (Sandbox Code Playgroud)

然后在BeautifulSoup方法中添加html5lib:

htmlDoc = bs4.BeautifulSoup(req1.text, 'html5lib')
print(htmlDoc)
Run Code Online (Sandbox Code Playgroud)