You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

已安装BeautifulSoup4但Jupyter Notebook导入失败,求排查方案

问题描述

在Jupyter Notebook中运行以下导入代码时触发ModuleNotFoundError:

from selenium import webdriver
import beautifulsoup4
import pandas as pd

报错详情:

ModuleNotFoundError                       Traceback (most recent call last)
Cell In [12], line 2
      1 from selenium import webdriver
----> 2 import beautifulsoup4
      3 import pandas as pd

ModuleNotFoundError: No module named 'beautifulsoup4'

但在终端执行pip install beautifulsoup4时,系统提示模块已安装:

(CodingFolder) user ~ % pip install beautifulsoup4
Requirement already satisfied: beautifulsoup4 in ./opt/anaconda3/envs/CodingFolder/lib/python3.9/site-packages (4.11.1)
Requirement already satisfied: soupsieve>1.2 in ./opt/anaconda3/envs/CodingFolder/lib/python3.9/site-packages (from beautifulsoup4) (2.3.2.post1)
解决思路
  • 环境不匹配是核心原因
    终端的pip指向CodingFolder虚拟环境,但Jupyter Notebook可能在使用其他Python环境(比如base环境)。解决步骤:

    1. 在Jupyter单元格中运行以下代码,查看当前Python路径:
      import sys
      print(sys.executable)
      
    2. 对比终端执行which python(Mac/Linux)或where python(Windows)的输出,若路径不同,说明环境不一致。
    3. 给Jupyter添加对应环境的内核:
      • 终端激活CodingFolder环境
      • 执行pip install ipykernel
      • 执行python -m ipykernel install --user --name=CodingFolder
      • 重启Jupyter,右上角切换到CodingFolder内核后重新运行代码。
  • 确认导入方式(可选优化)
    虽然import beautifulsoup4语法合法,但BeautifulSoup的标准导入方式是:

    from bs4 import BeautifulSoup
    

    建议使用这种方式,避免后续调用时的路径问题。

  • 校验pip与Python的对应关系
    终端执行pip --version查看其关联的Python路径,确保和python --version的路径一致。若不一致,改用python -m pip install beautifulsoup4强制安装到当前Python环境。

内容的提问来源于stack exchange,提问作者Niko

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 08:55:17