2016-03-16 70 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')