首页 > 解决方案 > 为什么我无法在 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 的虚拟环境中。

欢迎任何帮助找出问题的根源。

标签: pythonbeautifulsoupjupyter-lab

解决方案


您的问题出在这一行:

simple = BeautifulSoup('html_file','lxml')

特别是,您告诉 BeautifulSoup 解析文字字符串'html_file'而不是变量的内容html_file

将其更改为:

simple = BeautifulSoup(html_file,'lxml')

(注意周围没有引号html_file)应该给出预期的结果。


推荐阅读