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