python - 为什么我无法在 Jupyterlab 中使用 BeautifulSoup4 解析本地文件
问题描述
我正在关注一个网络教程,尝试使用 BeautifulSoup4 从 Jupyterlab 中的 html 文件(存储在我的本地 PC 上)中提取数据,如下所示:
from bs4 import BeautifulSoup
with open ('simple.html') as html_file:
simple = BeautifulSoup('html_file','lxml')
print(simple.prettify())
无论html文件中的内容是什么,而不是预期的html,我都会得到以下输出
<html>
<body>
<p>
html_file
</p>
</body>
</html>
我还使用 html 解析器 html.parser 尝试过它,我只是将html_file
其作为输出。我知道它可以找到该文件,因为当我从目录中删除代码后运行代码时,我得到一个 FileNotFoundError。
当我从同一目录以交互方式运行 python 时,它运行良好。我可以运行其他 BeautifulSoup 来解析网页。
我正在使用 Fedora 32 linux 和 Python3、Jupyterlab、BeautifulSoup4、requests、lxml 安装在使用 pipenv 的虚拟环境中。
欢迎任何帮助找出问题的根源。
解决方案
您的问题出在这一行:
simple = BeautifulSoup('html_file','lxml')
特别是,您告诉 BeautifulSoup 解析文字字符串'html_file'
而不是变量的内容html_file
。
将其更改为:
simple = BeautifulSoup(html_file,'lxml')
(注意周围没有引号html_file
)应该给出预期的结果。
推荐阅读
- python-3.x - 将文本从一个角移到另一角
- intellisense - C_CPP.intellisense 已禁用。如何再次启用
- git - git 是如何快速检测目录变化的?
- robotframework - 可以使用命令行参数调用 Robot Framework 测试套件吗?
- bash - 如何每 20 秒执行一次 bash 脚本?,好用睡眠和循环?
- pine-script - 使用 bar_index 作为其他最高()的长度
- python - 有没有办法防止python内部出现“连接错误”或“无网络”错误?
- php - php预填充文本区域
- python - 在graphviz python包中难以分离等级
- vb.net - VB.net:打印 RTL DGV 内容