61

安装 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")

我不知道为什么会出现以及如何解决它。

4

4 回答 4

114

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

BeautifulSoup( ... )

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

BeautifulSoup( ..., "html.parser" )

如果您愿意,还可以安装第 3 方解析器。

于 2015-11-04T00:14:53.807 回答
20

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

BeautifulSoup(html, "lxml")

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

安装 LXML 解析器

  • 在 Ubuntu (debian) 上

    apt-get install python-lxml 
    
  • Fedora(基于 RHEL)

    dnf install python-lxml
    
  • 使用画中画

    pip install lxml
    
于 2016-06-07T10:46:32.637 回答
5

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

pip install html5lib

然后在 BeautifulSoup 方法中添加 html5lib:

htmlDoc = bs4.BeautifulSoup(req1.text, 'html5lib')
print(htmlDoc)
于 2018-09-06T15:03:35.873 回答
3

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

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

但在某些情况下,您想使警告静音......因此这篇文章。

  • 从 BeautifulSoup 4 rev 460开始,警告消息不会出现在交互 ( REPL ) 模式下
  • 在以下位置有更多通才答案:如何禁用 python 警告以控制 Python 警告(TL;DL:PYTHONWARNINGS=ignore-Wignore
  • 通过添加到您的代码 显式抑制警告(bs4 ≥ rev 569 ):
    import warnings
    warnings.filterwarnings('ignore', category=GuessedAtParserWarning)
    
  • 通过让 bs4 认为您提供了解析器来作弊,即:
    bs4.BeautifulSoup(
      your_markup,
      builder=bs4.builder_registry.lookup(*bs4.BeautifulSoup.DEFAULT_BUILDER_FEATURES)
    )
    
于 2020-06-30T13:50:51.440 回答