【问题标题】:How to get rid of BeautifulSoup user warning?如何摆脱 BeautifulSoup 用户警告?
【发布时间】:2016-02-04 08:08:02
【问题描述】:

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

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

【问题讨论】:

  • 该消息正在告诉您确切的操作:BeautifulSoup([your markup], "html.parser")。你这样做了,看看你的输出是什么? BeautifulSoup 试图让您的生活更轻松。听汤。 :)
  • soup = BeautifulSoup(html)之类的代码更改为soup = BeautifulSoup(html, "html.parser")

标签: python beautifulsoup user-warning


【解决方案1】:

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

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

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

  • 从 BeautifulSoup 4 rev 460 开始,警告消息不会出现在交互 (REPL) 模式中
  • 有更多通才答案:How to disable python warnings 来控制 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)
    )
    

【讨论】:

  • 引用 PEP-20 第 2 点:“显式优于隐式”。当正确的修复是更少的代码时,不要隐藏警告。添加“html5lib”或“html.parser”在 IDE 或代码编辑器中是微不足道的,而在命令行中几乎是微不足道的。只是解决问题,不要隐藏症状。
【解决方案2】:

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

pip install html5lib

然后在 BeautifulSoup 方法中添加 html5lib:

htmlDoc = bs4.BeautifulSoup(req1.text, 'html5lib')
print(htmlDoc)

【讨论】:

    【解决方案3】:

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

    BeautifulSoup(html, "lxml")
    

    如果您使用的 Python 2 版本早于 2.7.3,或版本 早于 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
      

    【讨论】:

    • apt-get install python3-lxml
    【解决方案4】:

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

    BeautifulSoup( ... )
    

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

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

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

    【讨论】:

    • 查看 Beautiful Soup 的 installing a parser 文档了解一些常见解析器(html.parser、lxml、html5lib)的优缺点
    猜你喜欢
    • 2017-01-25
    • 1970-01-01
    • 1970-01-01
    • 2010-10-17
    • 2010-10-23
    • 2021-11-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多