在beautifulsoup中抑制url的警告

Jma*_*maa 18 python bs4

我正在使用Beautiful Soup 4来解析一些从互联网上删除的HTML格式的文本.有时这个文本只是一些网站的链接.事实上,BS4非常关注:

UserWarning: "http://example.com" looks like a URL. Beautiful Soup is not
an HTTP client. You should probably use an HTTP client to get the document
behind the URL, and feed that document to Beautiful Soup.
Run Code Online (Sandbox Code Playgroud)

我非常清楚这一事实,我只想解释文字输入,而不是讲课.我使用控制台来监视脚本的活动,并且它被一个非常生气的库弄得乱七八糟.

有什么方法来抑制或禁用此警告?

leg*_*gel 25

Wondercricket的解决方案丢失信息,因为它会强制引发异常(即使它被捕获).要简单地禁止警告并继续处理此工作:

import warnings
warnings.filterwarnings("ignore", category=UserWarning, module='bs4')
Run Code Online (Sandbox Code Playgroud)

  • 您可以通过在“filterwarnings”调用中添加“message='.*looks like a URL.*'”等关键字参数来避免抑制其他 Beautiful Soup 警告。 (5认同)
  • 还需要 `from bs4 import UserWarning` (3认同)
  • 最近的版本有什么变化吗?我得到 `ImportError: 无法从 'bs4' 导入名称 'UserWarning'` (3认同)
  • 最近版本更新:将 'UserWarning' 替换为 'MarkupResemblesLocatorWarning' ```from bs4 import BeautifulSoup, MarkupResemblesLocatorWarning warnings.filterwarnings('ignore', Category=MarkupResemblesLocatorWarning)``` (3认同)