Requests 是用Python语言编写,基于 urllib,采用 Apache2 Licensed 开源协议的 HTTP 库。它比 urllib 更加方便,可以节约我们大量的工作,完全满足 HTTP 测试需求。Requests 的哲学是以 PEP 20 的习语为中心开发的,所以它比 urllib 更加 Pythoner。更重要的一点是它支持 Python3 哦!

  • Beautiful is better than ugly.(美丽优于丑陋)
  • Explicit is better than implicit.(清楚优于含糊)
  • Simple is better than complex.(简单优于复杂)
  • Complex is better than complicated.(复杂优于繁琐)
  • Readability counts.(重要的是可读性)

一、安装 Requests

通过pip安装

pip install requests

或者,下载代码后安装:

$ git clone git://github.com/kennethreitz/requests.git
$ cd requests
$ python setup.py install

再懒一点,通过IDE安装吧,如pycharm!

二、发送请求与传递参数

先来一个简单的例子吧!让你了解下其威力:

import requests

r = requests.get(url='http://www.itwhy.org')    # 最基本的GET请求
print(r.status_code) # 获取返回状态
r = requests.get(url='http://dict.baidu.com/s', params={'wd':'python'}) #带参数的GET请求
print(r.url)
print(r.text) #打印解码后的返回数据

很简单吧!不但GET方法简单,其他方法都是统一的接口样式哦!

requests.get(‘https://github.com/timeline.json’) #GET请求
requests.post(“http://httpbin.org/post”) #POST请求
requests.put(“http://httpbin.org/put”) #PUT请求
requests.delete(“http://httpbin.org/delete”) #DELETE请求
requests.head(“http://httpbin.org/get”) #HEAD请求
requests.options(“http://httpbin.org/get”) #OPTIONS请求

PS:以上的HTTP方法,对于WEB系统一般只支持 GET 和 POST,有一些还支持 HEAD 方法。
带参数的请求实例:

import requests
requests.get('http://www.dict.baidu.com/s', params={'wd': 'python'}) #GET参数实例
requests.post('http://www.itwhy.org/wp-comments-post.php', data={'comment': '测试POST'}) #POST参数实例

POST发送JSON数据:

import requests
import json r = requests.post('https://api.github.com/some/endpoint', data=json.dumps({'some': 'data'}))
print(r.json())

定制header:

import requests
import json data = {'some': 'data'}
headers = {'content-type': 'application/json',
'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:22.0) Gecko/20100101 Firefox/22.0'} r = requests.post('https://api.github.com/some/endpoint', data=data, headers=headers)
print(r.text)

三、Response对象

使用requests方法后,会返回一个response对象,其存储了服务器响应的内容,如上实例中已经提到的 r.text、r.status_code……
获取文本方式的响应体实例:当你访问 r.text 之时,会使用其响应的文本编码进行解码,并且你可以修改其编码让 r.text 使用自定义的编码进行解码。

r = requests.get('http://www.itwhy.org')
print(r.text, '\n{}\n'.format('*'*79), r.encoding)
r.encoding = 'GBK'
print(r.text, '\n{}\n'.format('*'*79), r.encoding)

其他响应:

r.status_code #响应状态码
r.raw #返回原始响应体,也就是 urllib 的 response 对象,使用 r.raw.read() 读取
r.content #字节方式的响应体,会自动为你解码 gzip 和 deflate 压缩
r.text #字符串方式的响应体,会自动根据响应头部的字符编码进行解码
r.headers #以字典对象存储服务器响应头,但是这个字典比较特殊,字典键不区分大小写,若键不存在则返回None
#*特殊方法*#
r.json() #Requests中内置的JSON解码器
r.raise_for_status() #失败请求(非200响应)抛出异常

案例之一:

import requests

URL = 'http://ip.taobao.com/service/getIpInfo.php'  # 淘宝IP地址库API
try:
r = requests.get(URL, params={'ip': '8.8.8.8'}, timeout=1)
r.raise_for_status() # 如果响应状态码不是 200,就主动抛出异常
except requests.RequestException as e:
print(e)
else:
result = r.json()
print(type(result), result, sep='\n')

四、上传文件

使用 Requests 模块,上传文件也是如此简单的,文件的类型会自动进行处理:

import requests

url = 'http://127.0.0.1:5000/upload'
files = {'file': open('/home/lyb/sjzl.mpg', 'rb')}
#files = {'file': ('report.jpg', open('/home/lyb/sjzl.mpg', 'rb'))} #显式的设置文件名 r = requests.post(url, files=files)
print(r.text)

更加方便的是,你可以把字符串当着文件进行上传:

import requests

url = 'http://127.0.0.1:5000/upload'
files = {'file': ('test.txt', b'Hello Requests.')} #必需显式的设置文件名 r = requests.post(url, files=files)
print(r.text)

五、身份验证

基本身份认证(HTTP Basic Auth):

import requests
from requests.auth import HTTPBasicAuth r = requests.get('https://httpbin.org/hidden-basic-auth/user/passwd', auth=HTTPBasicAuth('user', 'passwd'))
# r = requests.get('https://httpbin.org/hidden-basic-auth/user/passwd', auth=('user', 'passwd')) # 简写
print(r.json())

另一种非常流行的HTTP身份认证形式是摘要式身份认证,Requests对它的支持也是开箱即可用的:

requests.get(URL, auth=HTTPDigestAuth('user', 'pass'))

六、Cookies与会话对象

如果某个响应中包含一些Cookie,你可以快速访问它们:

import requests

r = requests.get('http://www.google.com.hk/')
print(r.cookies['NID'])
print(tuple(r.cookies))

要想发送你的cookies到服务器,可以使用 cookies 参数:

import requests

url = 'http://httpbin.org/cookies'
cookies = {'testCookies_1': 'Hello_Python3', 'testCookies_2': 'Hello_Requests'}
# 在Cookie Version 0中规定空格、方括号、圆括号、等于号、逗号、双引号、斜杠、问号、@,冒号,分号等特殊符号都不能作为Cookie的内容。
r = requests.get(url, cookies=cookies)
print(r.json())

会话对象让你能够跨请求保持某些参数,最方便的是在同一个Session实例发出的所有请求之间保持cookies,且这些都是自动处理的,甚是方便。
下面就来一个真正的实例,如下是快盘签到脚本:

import requests

headers = {'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Encoding': 'gzip, deflate, compress',
'Accept-Language': 'en-us;q=0.5,en;q=0.3',
'Cache-Control': 'max-age=0',
'Connection': 'keep-alive',
'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:22.0) Gecko/20100101 Firefox/22.0'} s = requests.Session()
s.headers.update(headers)
# s.auth = ('superuser', '123')
s.get('https://www.kuaipan.cn/account_login.htm') _URL = 'http://www.kuaipan.cn/index.php'
s.post(_URL, params={'ac':'account', 'op':'login'},
data={'username':'****@foxmail.com', 'userpwd':'********', 'isajax':'yes'})
r = s.get(_URL, params={'ac':'zone', 'op':'taskdetail'})
print(r.json())
s.get(_URL, params={'ac':'common', 'op':'usersign'})

七、超时与异常

timeout 仅对连接过程有效,与响应体的下载无关。

>>> requests.get('http://github.com', timeout=0.001)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
requests.exceptions.Timeout: HTTPConnectionPool(host='github.com', port=80): Request timed out. (timeout=0.001)

所有Requests显式抛出的异常都继承自 requests.exceptions.RequestException:ConnectionError、HTTPError、Timeout、TooManyRedirects。

转自:http://www.itwhy.org/%E8%BD%AF%E4%BB%B6%E5%B7%A5%E7%A8%8B/python/python-%E7%AC%AC%E4%B8%89%E6%96%B9-http-%E5%BA%93-requests-%E5%AD%A6%E4%B9%A0.html

requests是python的一个HTTP客户端库,跟urllib,urllib2类似,那为什么要用requests而不用urllib2呢?官方文档中是这样说明的:

python的标准库urllib2提供了大部分需要的HTTP功能,但是API太逆天了,一个简单的功能就需要一大堆代码。

我也看了下requests的文档,确实很简单,适合我这种懒人。下面就是一些简单指南。

插播个好消息!刚看到requests有了中文翻译版,建议英文不好的看看,内容也比我的博客好多了,具体链接是:http://cn.python-requests.org/en/latest/(不过是v1.1.0版,另抱歉,之前贴错链接了)。

[转载]Python-第三方库requests详解的更多相关文章

  1. python第三方库requests详解

    Requests 是用Python语言编写,基于 urllib,采用 Apache2 Licensed 开源协议的 HTTP 库.它比 urllib 更加方便,可以节约我们大量的工作,完全满足 HTT ...

  2. 第三方库requests详解

    Requests 是用Python语言编写,基于 urllib,采用 Apache2 Licensed 开源协议的 HTTP 库.它比 urllib 更加方便,可以节约我们大量的工作,完全满足 HTT ...

  3. robot framework学习笔记之十一--第三方库requests详解

    一.安装 Requests 通过pip安装 pip install requests 或者,下载代码后安装: $ git clone git://github.com/kennethreitz/req ...

  4. python第三方库requests简单介绍

    一.发送请求与传递参数 简单demo: import requests r = requests.get(url='http://www.itwhy.org') # 最基本的GET请求 print(r ...

  5. Python-第三方库requests详解

    Requests 是用Python语言编写,基于 urllib,采用 Apache2 Licensed 开源协议的 HTTP 库.它比 urllib 更加方便,可以节约我们大量的工作,完全满足 HTT ...

  6. Python-第三方库requests详解(附requests中文官方教程)

    转自http://blog.csdn.net/cyjs1988/article/details/73294774 Python+requests中文官方教程: http://www.python-re ...

  7. python第三方库Requests的基本使用

    Requests 是用python语言编写,基于 urllib,采用 Apache2 Licensed 开源协议的 HTTP 库.它比 urllib 更加方便,可以节约我们大量的工作,完全满足 HTT ...

  8. 10.Python-第三方库requests详解(二)

    Requests 是用Python语言编写,基于 urllib,采用 Apache2 Licensed 开源协议的 HTTP 库.它比 urllib 更加方便,可以节约我们大量的工作,完全满足 HTT ...

  9. 转载:python文件打开方式详解——a、a+、r+、w+区别

    第一步 排除文件打开方式错误: r只读,r+读写,不创建      ###f.readline()是读取第一行,f.readlines()是读取全部并返回一个列表 w新建只写,w+新建读写,会将文件内 ...

随机推荐

  1. Winform端上传图片到服务器

    转载自  在winform实现文件上传到服务器 webform上传文件可能大家都写过很多,一个HtmlInputFile.PostedFile.SaveAs就搞定了,不过不知道大家有没有在winfor ...

  2. [转] Memcached参数设置 命令

    只是看到了..这些命令肯定是没问题的.. 笔者现在也还不会用..汗..先留着..找到怎么用了在回来修改.. memcached的基本设置: -p 监听的端口-l 连接的IP地址, 默认是本机-d st ...

  3. Yii2 使用 Joins 查询

    Join() JOIN_TYPE = INNER JOIN, LEFT OUTER JOIN, RIGHT OUTER JOIN, FULL OUTER JOIN 等等 语法 $query = new ...

  4. 一次插入多条记录 [mysql]

    调用多次INSERT语句不就可以插入多条记录了吗?但使用这种方法要增加服务器的负荷,因为,执行每一次SQL服务器都要同样对SQL进行分析.优化等操作.幸好MySQL提供了另一种解决方案,就是使用一条I ...

  5. oracle中的number类型

    number 数据类型 number (precision,scale) a)    precision表示数字中的有效位,如果没有指定precision的话,oracle将使用38作为精度: b)  ...

  6. IOC和bean容器

  7. 点击自动显示/隐藏DIV代码。(简单实用)

    注:本文由Colin撰写,版权所有!转载请注明原文地址,谢谢合作! 很多时候我们需要将DIV的信息默认为隐藏状态,只有当用户点击时才显示DIV中包含的提示文字.这类效果在互联网上应用得很多,但实现的方 ...

  8. input lable水平对齐

    1.CSS <style type="text/css">       input,label { vertical-align:middle;} </style ...

  9. C#深入浅出 关键字(一)

    1.this this关键字用于指示当前对象“自己”,来看一个例子,了解什么时候需要用this class Star { String name; int age; public void SetIn ...

  10. Android 4.4以上的存储读写权限

    最近遇到一个奇怪现象,直接往Android的SD卡根目录写入文件,报异常:open failed EACCES:permission denied. 已经在manifest.xml中加入android ...