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

标签 python python-3.x beautifulsoup html-parsing lxml

这是我的文件夹树:

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 .

关于python - 从(相对)父文件夹导入 BeautifulSoup,并在其旁边导入一个 html 解析器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48054837/

相关文章:

python - 如何让我的代码停止在网络爬虫中打印关键字

python - 如果我们可以使用 Selenium,为什么我们还需要像 BeautifulSoup 这样的解析器?

python - 从嵌套列表创建新列表并将字符串转换为 float

python - OpenAi Gym 安装 - python 版本不匹配

python - 调用重置函数时,仅清除最后一行条目

python - 汇总列表列表

python - 根据另一个 fixture 的值对值列表进行参数化

Python 使用进度条设置四步

python - WSGI 应用程序引发异常

python - 如何仅抓取同一类中的某些标签?