Python-urllib,urllib2,urllib3和请求模块之间有什么区别?

发布于 2021-02-02 23:19:52

在Python,有什么之间的差异urllib,urllib2,urllib3和``requests模块?为什么有三个?他们似乎在做同样的事情…

关注者
0
被浏览
128
1 个回答
  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

    我知道已经有人说过了,但我强烈建议你使用requestsPython软件包。

    如果你使用的是除python之外的语言,则可能是在考虑urllib并且urllib2易于使用,代码不多且功能强大,这就是我以前的想法。但是该requests程序包是如此有用且太短,以至于每个人都应该使用它。

    首先,它支持完全宁静的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
    

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

    • International Domains and URLs
    • Keep-Alive & Connection Pooling
    • Sessions with Cookie Persistence
    • Browser-style SSL Verification
    • Basic/Digest Authentication
    • Elegant Key/Value Cookies
    • Automatic Decompression
    • Unicode Response Bodies
    • Multipart File Uploads
    • Connection Timeouts
    • .netrc support
    • List item
    • Python 2.6—3.4
    • Thread-safe.


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看