urllib、urllib2、urllib3 和 requests 模块之间有什么区别? [英] What are the differences between the urllib, urllib2, urllib3 and requests module?

查看:53
本文介绍了urllib、urllib2、urllib3 和 requests 模块之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Python 中,urllib 之间有什么区别?a>、urllib2urllib3requests 模块?为什么是三个?他们似乎在做同样的事情......

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...

推荐答案

我知道已经有人说过了,但我强烈推荐 requests Python 包.

I know it's been said already, but I'd highly recommend the requests Python package.

如果您使用过 Python 以外的语言,您可能会认为 urlliburllib2 易于使用,代码不多,功能强大,就是这样我以前以为.但是 requests 包非常有用和简短,每个人都应该使用它.

If you've used languages other than python, you're probably thinking urllib and urllib2 are easy to use, not much code, and highly capable, that's how I used to think. But the requests package is so unbelievably useful and short that everyone should be using it.

首先,它支持完全宁静的 API,并且非常简单:

First, it supports a fully restful API, and is as easy as:

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,你都不必再次编码参数,它只需要一个字典作为参数就可以了:

Regardless of whether GET / POST, you never have to encode parameters again, it simply takes a dictionary as an argument and is good to go:

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

另外,它甚至有一个内置的 JSON 解码器(同样,我知道 json.loads() 不需要写太多,但这确实很方便):

Plus it even has a built in JSON decoder (again, I know json.loads() isn't a lot more to write, but this sure is convenient):

resp.json()

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

Or if your response data is just text, use:

resp.text

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

This is just the tip of the iceberg. This is the list of features from the requests site:

  • 国际域名和网址
  • 保持活动状态&连接池
  • 具有 Cookie 持久性的会话
  • 浏览器式 SSL 验证
  • 基本/摘要式身份验证
  • 优雅的键/值 Cookie
  • 自动减压
  • Unicode 响应体
  • 分段文件上传
  • 连接超时
  • .netrc 支持
  • 列表项
  • Python 2.6—3.4
  • 线程安全.

这篇关于urllib、urllib2、urllib3 和 requests 模块之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆