r=requests.get('url',auth=('user','pass'),params={},stream=True/False,headers={},cookies=cookies,allow_redirects=False,timeout=0.01)
auth为验证用户身份,这里的用户名和密码与登陆系统的用户名密码有所区别,auth不作为参数来传输即不是明文的,但依然包含在request请求中,一般会通过加密算法进行加密,如果接口开发带Auth接口,则此参数需要
params为传递的参数,字典{'key1': 'value1', 'key2': ['value2', 'value3']},一般会放到url后面
stream为原始响应内容
headers为请求头,字典{'user-agent': 'my-app/0.0.1'}
cookies为dict(cookies_are='working')
allow_redirects为允许重定向
timeout为超时时间
---------------------------------------------------------------------------------------
r=requests.post('url',data={},files=files)
data为传递的参数,字典{'key1': 'value1', 'key2': 'value2'}或元祖(('key1', 'value1'), ('key1', 'value2'))
files为上传的文件,{'file': open('report.xls', 'rb')}
------------------------------------------------------------------------------------
请求完成后,对获得的结果进行操作
r.status_code | 返回码 |
r.headers['content-type'] | 返回头的content-type内容 |
r.encoding | 返回结果的编码方式 |
r.text | 返回结果内容 |
r.json() | 返回结果的json格式 |
x=r.json() x['status'] x['message'] x['data']['name'] |
返回的json 状态码 message信息 ['data']['name']的值 |
安装requests库
Python的标准库中有urllib/urllib2/httplib,http库,httplib底层一点,第三方库有requests,安装requests (pip install requests),源码在C:Python27Libsite-packages equests路径下查看
>>> import requests
>>> r = requests.get('https://github.com/timeline.json') //GET请求
>>> r = requests.post("http://httpbin.org/post") //POST请求
>>> r = requests.put("http://httpbin.org/put") //PUT请求
>>> r = requests.delete("http://httpbin.org/delete") //DELETE请求
>>> r = requests.head("http://httpbin.org/get")
>>> r = requests.options("http://httpbin.org/get")
传递URL参数
GET请求中通常是这样的url http://xxxxx.org/?name=aaa&address=bbb
其中name和address均为传递的参数
>>> payload = {'key1': 'value1', 'key2': 'value2'}
>>> r = requests.get("http://httpbin.org/get", params=payload)
此时
>>> print(r.url)
http://httpbin.org/get?key2=value2&key1=value1
若payload的字典中有的值为None,则该键值不会被添加到URL的查询字符串里
也可以讲列表作为值传入:
>>> payload = {'key1': 'value1', 'key2': ['value2', 'value3']}
>>> r = requests.get('http://httpbin.org/get', params=payload)
>>> print(r.url)
http://httpbin.org/get?key1=value1&key2=value2&key2=value3
响应内容
>>> import requests
>>> r = requests.get('https://github.com/timeline.json')
>>> r.text
u'[{"repository":{"open_issues":0,"url":"https://github.com/...
Requests会自动解析来自服务器的内容,也可以更改文本编码r.encoding
>>> r.encoding
'utf-8'
>>> r.encoding = 'ISO-8859-1'
如果改变了编码,每次访问r.text, Requests都会使用r.encoding的新值进行解析,若HTTP和XML自身指定了编码,可以用r.content查看编码,再设置r.encoding为相应编码,这样就可以正确解析r.text了
以请求返回的二进制数据创建一张图片,你可以使用如下代码:
>>> from PIL import Image
>>> from io import BytesIO
>>> i = Image.open(BytesIO(r.content))
JSON响应内容
Requests 中也有一个内置的 JSON 解码器,助你处理 JSON 数据:
>>> import requests
>>> r = requests.get('https://github.com/timeline.json')
>>> r.json()
[{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...
检查是否请求成功使用r.raise_for_status()或者r.status_code
原始响应内容
如果想获取来自服务器的原始套接字响应,可以使用r.raw
>>> r = requests.get('https://github.com/timeline.json', stream=True)
>>> r.raw
<requests.packages.urllib3.response.HTTPResponse object at 0x101194810>
>>> r.raw.read(10)
'x1fx8bx08x00x00x00x00x00x00x03'
将文本流保存到文件:
with open(filename, 'wb') as fd:
for chunk in r.iter_content(chunk_size):
fd.write(chunk)
定制请求头
指定content-type
>>> url = 'https://api.github.com/some/endpoint'
>>> headers = {'user-agent': 'my-app/0.0.1'}
>>> r = requests.get(url, headers=headers)
信息源优先级:auth=参数 》 .netrc的设置 》 headers=xxx
POST请求
你的数据字典在发出请求时会自动编码为表单形式:
>>> payload = {'key1': 'value1', 'key2': 'value2'}
>>> r = requests.post("http://httpbin.org/post", data=payload)
>>> print(r.text)
{
...
"form": {
"key2": "value2",
"key1": "value1"
},
...
}
为data参数传入一个元祖列表:
>>> payload = (('key1', 'value1'), ('key1', 'value2'))
>>> r = requests.post('http://httpbin.org/post', data=payload)
>>> print(r.text)
{
...
"form": {
"key1": [
"value1",
"value2"
]
},
...
}
接受编码为 JSON 的 POST/PATCH 数据:
>>> import json
>>> url = 'https://api.github.com/some/endpoint'
>>> payload = {'some': 'data'}
>>> r = requests.post(url, data=json.dumps(payload))
或者
>>> url = 'https://api.github.com/some/endpoint'
>>> payload = {'some': 'data'}
>>> r = requests.post(url, json=payload)
POST一个Multipart-Encoded的文件
>>> url = 'http://httpbin.org/post'
>>> files = {'file': open('report.xls', 'rb')}
>>> r = requests.post(url, files=files)
>>> r.text
{
...
"files": {
"file": "<censored...binary...data>"
},
...
}
显式地设置文件名,文件类型和请求头:
>>> url = 'http://httpbin.org/post'
>>> files = {'file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})}
>>> r = requests.post(url, files=files)
>>> r.text
{
...
"files": {
"file": "<censored...binary...data>"
},
...
}
发送作为文件来接收的字符串:
>>> url = 'http://httpbin.org/post'
>>> files = {'file': ('report.csv', 'some,data,to,send
another,row,to,send
')}
>>> r = requests.post(url, files=files)
>>> r.text
{
...
"files": {
"file": "some,data,to,send\nanother,row,to,send\n"
},
...
}
响应状态码
>>> r = requests.get('http://httpbin.org/get')
>>> r.status_code
200
Requests还附带了一个内置的状态码查询对象:
>>> r.status_code == requests.codes.ok
True
如果发送了一个错误请求(一个 4XX 客户端错误,或者 5XX 服务器错误响应),我们可以通过 Response.raise_for_status() 来抛出异常:
>>> bad_r = requests.get('http://httpbin.org/status/404')
>>> bad_r.status_code
404
>>> bad_r.raise_for_status()
Traceback (most recent call last):
File "requests/models.py", line 832, in raise_for_status
raise http_error
requests.exceptions.HTTPError: 404 Client Error
此时
>>> r.raise_for_status()
None
响应头
查看服务器响应头:
>>> r.headers
{
'content-encoding': 'gzip',
'transfer-encoding': 'chunked',
'connection': 'close',
'server': 'nginx/1.0.4',
'x-runtime': '148ms',
'etag': '"e1ca502697e5c9317743dc078f67693f"',
'content-type': 'application/json'
}
问这些响应头字段:
>>> r.headers['Content-Type']
'application/json'
>>> r.headers.get('content-type')
'application/json'
Cookie
如果某个响应中包含一些 cookie,你可以快速访问它们:
>>> url = 'http://example.com/some/cookie/setting/url'
>>> r = requests.get(url)
>>> r.cookies['example_cookie_name']
'example_cookie_value'
发送cookie到服务器:、
>>> url = 'http://httpbin.org/cookies'
>>> cookies = dict(cookies_are='working')
>>> r = requests.get(url, cookies=cookies)
>>> r.text
'{"cookies": {"cookies_are": "working"}}'
Cookie的返回对象为RequestsCookieJar
>>> jar = requests.cookies.RequestsCookieJar()
>>> jar.set('tasty_cookie', 'yum', domain='httpbin.org', path='/cookies')
>>> jar.set('gross_cookie', 'blech', domain='httpbin.org', path='/elsewhere')
>>> url = 'http://httpbin.org/cookies'
>>> r = requests.get(url, cookies=jar)
>>> r.text
'{"cookies": {"tasty_cookie": "yum"}}'
重定向
除了HEAD,Requests会自动处理所有重定向,使用响应对象history方法来追踪重定向
Github 将所有的 HTTP 请求重定向到 HTTPS:
>>> r = requests.get('http://github.com')
>>> r.url
'https://github.com/'
>>> r.status_code
200
>>> r.history
[<Response [301]>]
如果你使用的是GET、OPTIONS、POST、PUT、PATCH 或者 DELETE,那么你可以通过 allow_redirects 参数禁用重定向处理:
>>> r = requests.get('http://github.com', allow_redirects=False)
>>> r.status_code
301
>>> r.history
[]
如果你使用了 HEAD,你也可以启用重定向:
>>> r = requests.head('http://github.com', allow_redirects=True)
>>> r.url
'https://github.com/'
>>> r.history
[<Response [301]>]
超时
告诉 requests 在经过以 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)
注意
timeout
仅对连接过程有效,与响应体的下载无关。 timeout
并不是整个下载响应的时间限制,而是如果服务器在 timeout
秒内没有应答,将会引发一个异常(更精确地说,是在timeout
秒内没有从基础套接字上接收到任何字节的数据时)If no timeout is specified explicitly, requests do not time out.
r = requests.get('https://github.com', timeout=5) //服务器发送第一个字节之前的时间
r = requests.get('https://github.com', timeout=(3.05, 27)) //第二个时间为客户端等待服务器发送请求的时间
r = requests.get('https://github.com', timeout=None) //request永远等待
错误与异常
遇到网络问题(如:DNS 查询失败、拒绝连接等)时,Requests 会抛出一个 ConnectionError 异常。
如果 HTTP 请求返回了不成功的状态码, Response.raise_for_status() 会抛出一个 HTTPError 异常。
若请求超时,则抛出一个 Timeout 异常。
若请求超过了设定的最大重定向次数,则会抛出一个 TooManyRedirects 异常。
所有Requests显式抛出的异常都继承自 requests.exceptions.RequestException 。
检查结果
用assert语句对返回结果中的字典数据进行断言
result=r.json()
print(result)
assert result['status']==200
assert result['message']=="success"
assert result['data']['name']=="发布会"
如果用单元测试框架unittest.TestCse则用断言
self.assertEqual ( result['status'] , 200 )
....
高级用法
http://cn.python-requests.org/zh_CN/latest/user/advanced.html#advanced