lxml/BeautifulSoup解析器警告

Tee*_*kin 5 python lxml beautifulsoup python-3.x

使用Python 3,我试图解析丑陋的HTML(不受我的控制),使用lxmlBeautifulSoup,如下所述:http://lxml.de/elementsoup.html

具体来说,我想使用lxml,但我想使用BeautifulSoup,因为就像我说的那样,它是丑陋的HTML并且lxml会自己拒绝它.

上面的链接说:"你需要做的就是将它传递给fromstring()函数:"

from lxml.html.soupparser import fromstring
root = fromstring(tag_soup)
Run Code Online (Sandbox Code Playgroud)

这就是我正在做的事情:

URL = 'http://some-place-on-the-internet.com'
html_goo = requests.get(URL).text
root = fromstring(html_goo)
Run Code Online (Sandbox Code Playgroud)

它的工作原理是我可以在那之后操作HTML.我的问题是每次运行脚本时,都会收到这个恼人的警告:

/usr/lib/python3/dist-packages/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")

  markup_type=markup_type))
Run Code Online (Sandbox Code Playgroud)

我的问题可能很明显:我自己并没有实例化BeautifulSoup.我已经尝试将建议的参数添加到fromstring函数中,但这只是给了我错误:TypeError: 'str' object is not callable.到目前为止,在线搜索已证明无效.

我想摆脱那条警告信息.感谢提前感谢.

Win*_*oon 14

对于其他人 init 像:

soup = BeautifulSoup(html_doc)
Run Code Online (Sandbox Code Playgroud)

soup = BeautifulSoup(html_doc, 'html.parser')
Run Code Online (Sandbox Code Playgroud)

反而


Tee*_*kin 7

我不得不阅读lxml's和BeautifulSoup的源代码来解决这个问题.

我在这里发布自己的答案,万一其他人可能会在将来需要它.

fromstring有问题的函数定义如下:

def fromstring(data, beautifulsoup=None, makeelement=None, **bsargs):
Run Code Online (Sandbox Code Playgroud)

这些**bsargs参数最终被发送到BeautifulSoup构造函数,它被调用为(在另一个函数中_parse):

tree = beautifulsoup(source, **bsargs)
Run Code Online (Sandbox Code Playgroud)

BeautifulSoup构造函数定义如下:

def __init__(self, markup="", features=None, builder=None,
             parse_only=None, from_encoding=None, exclude_encodings=None,
             **kwargs):
Run Code Online (Sandbox Code Playgroud)

现在,回到问题中的警告,建议将参数"html.parser"添加到BeautifulSoup的构造函数中.根据这个,这将是命名的论点features.

由于fromstring函数会将命名参数传递给BeautifulSoup的构造函数,因此我们可以通过命名fromstring函数的参数来指定解析器,如下所示:

root = fromstring(clean, features='html.parser')
Run Code Online (Sandbox Code Playgroud)

噗.警告消失了.