【问题标题】:Python cannot find module Request from urllib.requestPython 找不到来自 urllib.request 的模块请求
【发布时间】:2018-02-22 16:10:18
【问题描述】:

Python 找不到来自 urllib.request 的模块请求

更新: - 我尝试用 python3 运行它......请参阅:

martin@linux-3645:~/dev/python> Python3 w9.py
If 'Python3' is not a typo you can use command-not-found to lookup the package that contains it, like this:
    cnf Python3
martin@linux-3645:~/dev/python> 

在 Python 代码中尝试从 urllib.request 导入 Request 时,找不到包。

>>> from urllib.request import urlopen as uReq
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named request

查看我正在尝试运行的代码...:

import bs4
from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup

my_url = "https://wordpress.org/plugins/participants-database/"
uClient = uReq(my_url)
page_html = uClient.read()
uClient.close()
page_soup = soup(page_html, "html.parser")

ttt = page_soup.find("div", {"class":"plugin-meta"})
text_nodes = [node.text.strip() for node in ttt.ul.findChildren('li')[:-1:2]]

不幸的是,这会导致:

martin@linux-3645:~/dev/python> python w9.py
Traceback (most recent call last):
File "w9.py", line 3, in <module>
from urllib.request import urlopen as uReq
ImportError: No module named request
martin@linux-3645:~/dev/python> 

嗯:Python 2 中没有 urllib.request 模块,该模块仅存在于 Python 3 中。

我做了一些搜索并找到了一个可能的解决方法:看到这个 soultion: 我可以使用 urllib2 代替:

from urllib2 import Request

来自模块文档的顶部: 注意: urllib2 模块在 Python 3 中被拆分为多个名为 urllib.request 和 urllib.error 的模块。将源代码转换为 Python 3 时,2to3 工具会自动调整导入。

但是等等:我以为我已经运行 Python 3 并且我继续使用那个版本;我试图执行的代码显然是为 Python 3 设计的。

这里出了什么问题?

【问题讨论】:

  • 您确定您正在使用命令python w9.py 运行Python 3?
  • 只是让您知道:是的,这是您尝试使用 Python 2.x 运行时会遇到的预期错误
  • 也许添加一个shebang或使用python3调用
  • 大家好 - 非常感谢您的快速回复;请参阅帖子中的更新。我添加了命令和回复....我实际上不确定那里出了什么问题...。期待您的来信
  • 运行python3时小写p

标签: python linux python-3.x python-2.7 beautifulsoup


【解决方案1】:

您的示例代码适用于 python3。请注意,您必须以小写形式运行“python3”,而不是 Python3。

使用您发布的示例代码,您不会在屏幕上看到任何输出,因为您没有要求任何输出。

如果在最后加上print(text_nodes),会得到如下输出:

['版本:1.7.7.7','活动安装:10,000+','测试到: 4.9.4']

【讨论】: