What are the differences between the urllib, urllib2, urllib3 and requests module?

后端 未结 11 2500
隐瞒了意图╮
隐瞒了意图╮ 2020-11-22 04:19

In Python, what are the differences between the urllib, urllib2, urllib3 and requests modules? Why are there three? They seem to do the same thing...

11条回答
  •  梦谈多话
    2020-11-22 04:52

    To get the content of a 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.
    

    It's hard to write Python2 and Python3 and request dependencies code for the responses because they urlopen() functions and requests.get() function return different types:

    • Python2 urllib.request.urlopen() returns a http.client.HTTPResponse
    • Python3 urllib.urlopen(url) returns an instance
    • Request request.get(url) returns a requests.models.Response

提交回复
热议问题