python - BeautifulSoup4导入错误

标签 python html python-3.x beautifulsoup importerror

我正在尝试构建一个Python代码来检查字符串是否包含HTML代码。我已经多次尝试使用 pip3 install beautifulsoup4pip3 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/

相关文章:

python - 在 pymongo 中将 writeConcern 级别设置为未确认

python - Matplotlib;使用不同的轴标签制作不同的子图

html - 通过 'View Source' 显示的 HTML 是否与(Firebug)开发人员工具中显示的 HTML 不同?

javascript - 使用 CSS Bootstrap 类将 HTML 页面转换为 PDF

python - python 中的图像数组

python-3.x - 使用 sklearn 运行线性回归时输出系数

python - 在运行时将文件中的每个段落读取到多个列表中

html - CSS "full width"部分在移动设备上无法正常工作

python - 使用seaborn时条件和输入之间的形状不一致

python - 使用python将日志文件转换为字典格式