2016-03-16 71 views
10

我使用美丽的汤4来解析一些HTML格式的文本,从互联网上刮。有时候这段文字只是一些网站的链接。事实上,BS4非常横约:禁止在美丽的URL的警告

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. 

我很明白这个道理,我只是想解释文本输入,没有得到讲座。我使用控制台来监视脚本的活动,并且它被一个非常生气的图书馆所混淆。

任何方法来抑制或禁用此警告?

+0

Catch'UserWarning'。 –

+0

@LutzHorn它不是一个例外,它直接打印到控制台,并且不会停止程序的执行。 – Jmaa

+0

@jDo:使用try ...的一种偏见,除非这种方式不起作用。 – Jmaa

回答

0

更新

这个答案已经过时,因为@legel状态,会导致信息丢失。请参考他的回答了合适的解决方案


您可以像您可以exceptions使用warnings模块赶上warnings

import warnings 
import bs4 

warnings.filterwarnings('error') 
try: 
    soup = bs4.BeautifulSoup('http://stackoverflow.com/') 
except UserWarning: 
    print('I caught the warning') 

>>> I caught the warning 

12

通过Wondercricket该解决方案失去了信息,因为它会强制引发异常(即使它被捉住)。要简单地禁止警告并继续处理此作品:

import warnings 
warnings.filterwarnings("ignore", category=UserWarning, module='bs4')