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

Python 2.7 cannot find module Request from urllib.request

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

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

Python2中没有urllib.request模块,那个模块only exists in Python 3.

改用urllib2

from urllib2 import Request

从模块文档的顶部开始:

Note: The urllib2 module has been split across several modules in Python 3 named urllib.request and urllib.error. The 2to3 tool will automatically adapt imports when converting your sources to Python 3.

如果您正在学习某种教程或课程,您可能需要安装 Python3 并继续使用该版本;您尝试执行的代码显然是为 Python 3.

设计的