首页 > 解决方案 > `没有名为'urllib2'的模块-我如何在Python中使用它,以便我可以提出请求

问题描述

Python新手,只是不确定如何为python做什么

我想使用urllib2-Request拨打电话 我该怎么做,例如在 repl 中。我想不出正确的方法

$ python3
Python 3.7.3 (default, Apr  3 2019, 05:39:12) 
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from urllib2 import Request, urlopen, URLerror, HTTPerror
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'urllib2'
>>> from urllib2 import Request, urlopen, URLerror, HTTPerror
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'urllib2'
>>> import Request
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'Request'
>>> import urllib2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'urllib2'
>>> 

...
req = Request(URL, json_message) #(URL and json_message defined but not shown here)

...

我是否必须将 urllib2 单独安装到系统中?就像我说的只是一个不知道步骤和语法的 Python 新手。谢谢!

我正在使用的示例有

from urllib2 import Request, urlopen, URLError, HTTPError

然后使用Request(...,但是当我在 python3 repl 中尝试时,我得到了

$ python3
Python 3.7.3 (default, Apr  3 2019, 05:39:12) 
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from urllib2 import Request
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'urllib2'
>>> 

标签: python-3.ximporturllib2

解决方案


python3中没有urllib2;有关更多详细信息,请参阅此问题。(这里的背景故事的简短版本是 Python2 和 Python3 是完全不同的飞行类型;并非 Py2 中的所有 stdlib 库都在 Py3 中可用。)

相反,尝试urllib(类似的 API);

from urllib import request

您可以点击此处的 urllib 文档,这可能会有所帮助。


推荐阅读