首页 > 解决方案 > 从 bs4 导入时如何绕过 ModuleNotFoundError?

问题描述

试图构建一个程序来从 html 中提取文本以进行翻译。我在命令提示符下安装了 python 和 bs4,并从另一个人那里复制了一些应该做我想做的事情的代码。每次我在 PyCharm 中运行它时,都会出现错误。我不确定如何处理这个问题。

编辑:我弄清楚发生了什么。我将 import bs4 添加到我的 python 文件中

从 urllib.request 导入 urlopen

从 bs4 导入 BeautifulSoup

进口bs4

在此之后,windows 询问我是否要安装 bs4(以前从未发生过这种情况)。我就是这样安装的。

然后我将 bs4 添加到汤变量 soup = bs4.BeautifulSoup(html, "html.parser")

运行脚本,它正在做我想要的。

import urllib
from bs4 import BeautifulSoup

url = "https://en.wikipedia.org/wiki/Russian_playing_cards"

html = urllib.urlopen(url).read()
soup = BeautifulSoup(html)

# kill all script and style elements
for script in soup(["script", "style"]):
    script.extract()    # rip it out

# get text
text = soup.get_text()

# break into lines and remove leading and trailing space on each
lines = (line.strip() for line in text.splitlines())
# break multi-headlines into a line each
chunks = (phrase.strip() for line in lines for phrase in line.split("  "))
# drop blank lines
text = '\n'.join(chunk for chunk in chunks if chunk)

print(text)

标签: python-3.x

解决方案


推荐阅读