已安装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环境)。解决步骤:- 在Jupyter单元格中运行以下代码,查看当前Python路径:
import sys print(sys.executable) - 对比终端执行
which python(Mac/Linux)或where python(Windows)的输出,若路径不同,说明环境不一致。 - 给Jupyter添加对应环境的内核:
- 终端激活
CodingFolder环境 - 执行
pip install ipykernel - 执行
python -m ipykernel install --user --name=CodingFolder - 重启Jupyter,右上角切换到
CodingFolder内核后重新运行代码。
- 终端激活
- 在Jupyter单元格中运行以下代码,查看当前Python路径:
确认导入方式(可选优化)
虽然import beautifulsoup4语法合法,但BeautifulSoup的标准导入方式是:from bs4 import BeautifulSoup建议使用这种方式,避免后续调用时的路径问题。
校验pip与Python的对应关系
终端执行pip --version查看其关联的Python路径,确保和python --version的路径一致。若不一致,改用python -m pip install beautifulsoup4强制安装到当前Python环境。
内容的提问来源于stack exchange,提问作者Niko
相关产品推荐
相关产品推荐

