【发布时间】:2018-10-07 07:37:40
【问题描述】:
使用 Python 3,我试图通过将 lxml 与 BeautifulSoup 一起使用来解析丑陋的 HTML(不受我控制),如下所述:http://lxml.de/elementsoup.html
具体来说,我想使用 lxml,但我想使用 BeautifulSoup,因为就像我说的,它是丑陋的 HTML,lxml 会自行拒绝它。
上面的链接说:“你需要做的就是将它传递给 fromstring() 函数:”
from lxml.html.soupparser import fromstring
root = fromstring(tag_soup)
这就是我正在做的事情:
URL = 'http://some-place-on-the-internet.com'
html_goo = requests.get(URL).text
root = fromstring(html_goo)
它工作,因为在那之后我可以很好地操作 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))
我的问题可能很明显:我自己没有实例化 BeautifulSoup。我尝试将建议的参数添加到fromstring 函数中,但这只是给了我错误:TypeError: 'str' object is not callable。到目前为止,在线搜索已被证明是徒劳的。
我想去掉那个警告信息。感谢您的帮助,在此先感谢。
【问题讨论】:
-
你试过
root = lxml.html.soupparser.fromstring(html_goo)吗? -
那行不通,因为
lxml是一个模块。但我试过了,它给了我:NameError: name 'lxml' is not defined(我认为这是有道理的) -
不能用
soupparser.fromstring(html_goo)调用吗?当这直接来自他们的文档时,我很惊讶它不起作用:p -
不,运行 soupparser.fromstring(...) 而不是 fromstring(...) 会产生相同的结果。我也觉得这很奇怪。
-
没问题! ^^ 您的解决方案几乎使用与我上一条评论完全相同的推理,您可以通过 fromstring() 传递构造函数参数,这对您找到解决方案很有帮助!祝你好运!
标签: python python-3.x beautifulsoup lxml