Skip to main content
 首页 » 编程设计

python之从(相对)父文件夹导入 BeautifulSoup,并在其旁边导入一个 html 解析器

2025年01月19日7over140

这是我的文件夹树:

script/ 
    main.py 
    dependencies/ 
        bs4/ 
            ... 
        requests/ 
            ... 

下面是我如何从 main.py 导入模块:

import dependencies.requests as requests 
import dependencies.bs4 as bs4 

脚本似乎工作得很好,但我不知道如何将 html 解析器添加到 dependencies\ 中以与 BeautifulSoup 一起工作。所以目前在 main.py 中我发出以下 GET 请求:

response = requests.get(url) 

然后尝试解析它:

parsed_html = bs4.BeautifulSoup(response.content, "lxml") 

然后我得到以下异常:

File "C:\Users\usr\Desktop\script\dependencies\bs4\__init__.py", line 165, in __init__ 
% ",".join(features)) 
 
dependencies.bs4.FeatureNotFound: Couldn't find a tree builder with the features you requested: lxml. Do you need to install a parser library? 

任何帮助将不胜感激。

此外,默认的 "html.parser" 会抛出相同的异常。

请您参考如下方法:

您应该将 PYTHONPATH 扩展到安装 lxml 或 html.parser 的文件夹。这样,“python”就会知道在哪个特定位置搜索您的包裹。

在任何一种情况下,您都在创建自己的具有依赖关系的文件夹结构,因为有用于此的工具,例如 virtualenv .