在Python中,urllib, urllib2, urllib3和请求模块之间有什么区别?为什么有三个?他们似乎在做同样的事情……


当前回答

获取url的内容:

try: # Try importing requests first.
    import requests
except ImportError: 
    try: # Try importing Python3 urllib
        import urllib.request
    except AttributeError: # Now importing Python2 urllib
        import urllib


def get_content(url):
    try:  # Using requests.
        return requests.get(url).content # Returns requests.models.Response.
    except NameError:  
        try: # Using Python3 urllib.
            with urllib.request.urlopen(index_url) as response:
                return response.read() # Returns http.client.HTTPResponse.
        except AttributeError: # Using Python3 urllib.
            return urllib.urlopen(url).read() # Returns an instance.

很难为响应编写Python2和Python3和请求依赖代码,因为它们的urlopen()函数和requests.get()函数返回不同的类型:

Python2 urllib.request.urlopen()返回一个http.client.HTTPResponse Python3 urllib.urlopen(url)返回一个实例 Request Request .get(url)返回一个requests.models.Response

其他回答

获取url的内容:

try: # Try importing requests first.
    import requests
except ImportError: 
    try: # Try importing Python3 urllib
        import urllib.request
    except AttributeError: # Now importing Python2 urllib
        import urllib


def get_content(url):
    try:  # Using requests.
        return requests.get(url).content # Returns requests.models.Response.
    except NameError:  
        try: # Using Python3 urllib.
            with urllib.request.urlopen(index_url) as response:
                return response.read() # Returns http.client.HTTPResponse.
        except AttributeError: # Using Python3 urllib.
            return urllib.urlopen(url).read() # Returns an instance.

很难为响应编写Python2和Python3和请求依赖代码,因为它们的urlopen()函数和requests.get()函数返回不同的类型:

Python2 urllib.request.urlopen()返回一个http.client.HTTPResponse Python3 urllib.urlopen(url)返回一个实例 Request Request .get(url)返回一个requests.models.Response

一个相当大的区别是关于将Python2移植到Python3。python3及其移植到urllib的方法不存在Urllib2。 因此,如果你正在大量使用它,并希望将来迁移到Python3,请考虑使用urllib。 然而,2to3工具将自动为您做大部分工作。

我知道已经说过了,但是我强烈推荐requests Python包。

如果您使用过python以外的语言,您可能会认为urllib和urllib2易于使用,代码不多,功能强大,这是我过去的想法。但是请求包非常有用且简短,每个人都应该使用它。

首先,它支持一个完全restful的API,并且非常简单:

import requests

resp = requests.get('http://www.mywebsite.com/user')
resp = requests.post('http://www.mywebsite.com/user')
resp = requests.put('http://www.mywebsite.com/user/put')
resp = requests.delete('http://www.mywebsite.com/user/delete')

不管是否GET / POST,你都不需要再次编码参数,它只是将字典作为参数,并且很好地运行:

userdata = {"firstname": "John", "lastname": "Doe", "password": "jdoe123"}
resp = requests.post('http://www.mywebsite.com/user', data=userdata)

此外,它甚至有一个内置的JSON解码器(再次强调,我知道JSON .loads()不是很多东西要写,但这肯定很方便):

resp.json()

或者如果你的响应数据只是文本,使用:

resp.text

这只是冰山一角。下面是请求站点的功能列表:

国际域名和网址 保持连接和连接池 具有Cookie持久性的会话 浏览器式SSL验证 基本/摘要式身份验证 优雅的键/值cookie 自动减压 Unicode响应体 Multipart File上传 连接超时 . netrc支持 列表项 Python 2.7, 3.6-3.9 线程安全的。

我喜欢urllib。urllib2中似乎不存在urllib2。

>>> urllib.urlencode({'abc':'d f', 'def': '-!2'})
'abc=d+f&def=-%212'

只是为了补充现有的答案,我没有看到任何人提到python requests不是一个原生库。如果您可以添加依赖项,那么请求就可以了。然而,如果你试图避免添加依赖项,urllib是一个已经可用的原生python库。