python - Installation of BS4 successful, python not recognising
问题描述
I hope that you are well. I have tried searching the other threads about my issue, but I have yet to find a solution. Attached below are the screenshots of my work and methods to install the bs4 module, and the error I encounter. I am more than willing to attach more screenshots if required. Here is the command prompt telling me that the installation was successful
import csv
import requests
from bs4 import BeautifulSoup4 as beauti
url = 'https://report.boonecountymo.org/mrcjava/servlet/SH01_MP.I00290s?max_rows=500'
response = requests.get(url, headers={'User-Agent': 'Mozilla/5.0'})
html = response.content
soup = BeautifulSoup(html)
table = soup.find('tbody', attrs={'class': 'stripe'})
list_of_rows = []
for row in table.findAll('tr'):
list_of_cells = []
for cell in row.findAll('td'):
text = cell.text.replace(' ', '')
list_of_cells.append(text)
list_of_rows.append(list_of_cells)
outfile = open("./inmates.csv", "wb")
writer = csv.writer(outfile)
writer.writerow(["Last", "First", "Middle", "Gender", "Race", "Age", "City", "State"])
writer.writerows(list_of_rows)
Below is IDLE giving me the error:
Traceback (most recent call last):
File "C:\Users\aditi\Desktop\webscraper.py", line 3, in <module>
from bs4 import BeautifulSoup4 as beauti
ImportError: cannot import name 'BeautifulSoup4' from 'bs4' (C:\Users\aditi\AppData\Local\Programs\Python\Python38-32\lib\site-packages\bs4\__init__.py)
解决方案
There's spelling mistake in the import statement!
It's BeautifulSoup and not BeautifulSoup4
from bs4 import BeautifulSoup as beauti
EDIT
Also I would recommend to stick to what you import like,
- You are importing BeautifulSoup4 but in this line below, you are using BeautifulSoup() and not BeautifulSoup4()
soup = BeautifulSoup(html)
- Importing BeautifulSoup4 as beauti and not using the variable 'beauti' anywhere.
We mostly stick with BeautifulSoup() and I also recommend you to do so.
I just found that this issue was previously asked and resolved here, check it out!
推荐阅读
- c - 使用 C 代码从 DFRWS 2007 数据集中检索 PPT 文件
- javascript - 您可以替换 Visual Studio 代码中所有打开文件中的变量及其值吗?
- deep-learning - 批量标准化对小型网络有用吗?
- facebook - Messaging_Referrals webhook 在 Facebook 页面中不起作用
- c++ - IO 完成端口返回 NULL 完成键
- design-patterns - 通过外键创建相关模型的流程
- javascript - 堆叠时间范围 svg rects,因此它们不会重叠
- javascript - 当单击时的 HTMLbuttonElement 无法识别目标函数时,如何解决未捕获的 ReferenceError
- web - 从 Web 浏览器发送信标信号
- javascript - 验证 2 组或更多组单选按钮,每组包含 4 个单选按钮