r=requests.get('url',auth=('user','pass'),params={},stream=True/False,headers={},cookies=cookies,allow_redirects=False,timeout=0.01) html
auth为验证用户身份,这里的用户名和密码与登录系统的用户名密码有所区别,auth不做为参数来传输即不是明文的,但依然包含在request请求中,通常会经过加密算法进行加密,若是接口开发带Auth接口,则此参数须要python
params为传递的参数,字典{'key1': 'value1', 'key2': ['value2', 'value3']},通常会放到url后面nginx
stream为原始响应内容git
headers为请求头,字典{'user-agent': 'my-app/0.0.1'}github
cookies为dict(cookies_are='working')算法
allow_redirects为容许重定向json
timeout为超时时间api
---------------------------------------------------------------------------------------服务器
r=requests.post('url',data={},files=files) cookie
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']的值 |
Python的标准库中有urllib/urllib2/httplib,http库,httplib底层一点,第三方库有requests,安装requests (pip install requests),源码在C:\Python27\Lib\site-packages\requests路径下查看
>>> 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")
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))
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) '\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03'
将文本流保存到文件:
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
你的数据字典在发出请求时会自动编码为表单形式:
>>> 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\nanother,row,to,send\n')} >>> 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,你能够快速访问它们:
>>> 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