我正在尝试构建一个Python代码来检查字符串是否包含HTML代码。我已经多次尝试使用 pip3 install beautifulsoup4
和 pip3 install lxml
重新安装 BeautifulSoup4 库,它已经向我展示了这一点:
Requirement already satisfied: beautifulsoup4
但是每当我尝试导入 beautifulsoup 时,都会出现以下错误代码:
bs4.FeatureNotFound: Couldn't find a tree builder with the features you requested
我应该怎样做才能正确导入beautifulsoup库?
这是代码块:
from bs4 import BeautifulSoup
body = "..."
bool(BeautifulSoup(body, "body.parser").find())
感谢任何帮助。 :)
最佳答案
我首先考虑查询中的第一句话,“我正在尝试构建一个 python 代码来检查字符串是否包含 HTML 代码。”
BeautifulSoup 很可能不是人们会使用的工具,因为它被设计为几乎可以接受任何字符串作为输入,并为该字符串生成经过解析的 HTML 结构。
例如,在这里我输入一个没有标签的字符串,BS 返回一个完整的页面,甚至为该页面生成一个 body
元素。
>>> import bs4
>>> s = 'this represents just about any string'
>>> soup = bs4.BeautifulSoup(s, 'lxml')
>>> soup
<html><body><p>this represents just about any string</p></body></html>
>>> soup.find_all('body')
[<body><p>this represents just about any string</p></body>]
这是使用 HTMLParser 的另一种有点粗糙的方法。 HTMLParser 位于标准 Python 库中。
>>> from html.parser import HTMLParser
>>> class IsItHTML(HTMLParser):
... def __init__(self):
... HTMLParser.__init__(self)
... self.found = False
... def handle_starttag(self, tag, attrs):
... self.found = True
... def __call__(self):
... return self.found
...
>>> isitHTML = IsItHTML()
>>> s = 'this represents just about any string'
>>> isitHTML.feed(s)
>>> isitHTML()
False
>>> s = '<body>something</body>'
>>> isitHTML.feed(s)
>>> isitHTML()
True
我对这种方法的主要批评是它涉及遍历 HTML 输入中的每个标签。
关于你的第二个主要问题:如何正确导入 BS?我认为你正在这样做。问题似乎出在 BeautifulSoup(body, "body.parser").find()
上。我不知道这意味着什么。
关于python - BeautifulSoup4导入错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47716699/