ModuleNotFoundError:没有名为“ bs4”的模块

时间:2019-01-15 15:12:36

标签: python-3.x beautifulsoup

当我尝试这样导入BeautifulSoup

from bs4 import BeautifulSoup

当我运行代码时,出现此错误消息。 ModuleNotFoundError: No module named 'bs4

如果有人知道如何解决此问题,那就太好了!

编辑(我的代码)

import os
import csv
import requests
import bs4

requete = requests.get("https://url")
page = requete.content
soup = BeautifulSoup(page)

h1 = soup.find("h1", {"class": "page_title"})
print(h1.string)

3 个答案:

答案 0 :(得分:1)

执行pip install bs4,这将解决您的错误。如果您安装了不同版本的Python,请根据需要尝试使用pip2pip3

pip2 install bs4 # for Python2
pip3 install bs4 # for Python3

答案 1 :(得分:0)

您a)尚未安装BeautifulSoup或b)没有看到您的代码,只能猜测您的代码中有bs4

即。

soup = bs4.BeautifulSoup(html, 'html.parser')

应将其更改为:

soup = BeautifulSoup(html, 'html.parser')

OR

您可以保留:

soup = bs4.BeautifulSoup(html, 'html.parser')

但随后您需要将导入内容设置为:

import bs4

完整代码:选项1

import os
import csv
import requests
import bs4     #<-----------------------NOTICE

requete = requests.get("https://url")
page = requete.content
soup = bs4.BeautifulSoup(page)  #<-----------------------NOTICE

h1 = soup.find("h1", {"class": "page_title"})
print(h1.string)

完整代码:选项2

import os
import csv
import requests
from bs4 import BeautifulSoup   #<-----------------------NOTICE

requete = requests.get("https://url")
page = requete.content
soup = BeautifulSoup(page)  #<-----------------------NOTICE

h1 = soup.find("h1", {"class": "page_title"})
print(h1.string)

答案 2 :(得分:0)

如果您使用的是PyCharm,请关闭并重新启动PyCharm。然后将鼠标光标移到bs4上,直到出现红色灯泡。使用第一个意图操作-“安装beautifulsoup”,然后PyCharm将从那里解决问题。

我遇到了同样的问题,并且在重新启动PyCharm之前,意图操作不起作用。