requests庫快速入門
(參照官方文檔翻譯整理,翻譯不易,喜歡的朋友可以點個贊、評論或者關注一下。如果喜歡的讀者多,翻譯完成後會全部共享給大家,謝謝支持!)
原官方文檔截圖:
一、安裝
requests的安裝有一下幾種方式:
1.在命令行中,輸入以下命令(已安裝python):
$ git clone git://github.com/kennethreitz/requests.git
2.通過源代碼安裝
$ curl -OL https://github.com/kennethreitz/requests/tarball/master
或者:
源代碼下載好後,進入源代碼所在的文件夾,輸入如下命令:
python setup.py install
二、快速入門
requests是用來請求網絡資源,並可進行簡單處理的一個庫,使用方法很簡單
>>> import requests #導入requests庫
requests的HTTP請求主要有如下幾種方法:
>>> r = requests.get('https://api.github.com/events')
>>> r = requests.post('http://httpbin.org/post', data = {'key':'value'})
>>> r = requests.put('http://httpbin.org/put', data = {'key':'value'})
>>> r = requests.delete('http://httpbin.org/delete')
>>> r = requests.head('http://httpbin.org/get')
>>> r = requests.options('http://httpbin.org/get')
在請求網絡資源時,還可以在url鏈接中添加參數,參數以字典形式,通過params關鍵字添加到url中:
>>> keywords = {‘key1’ : ‘value1’, ‘key2’ : [‘value2’, ‘value3’]}
>>> r = requests.get(‘http://www.baidu.com/get’, params = keywords)
其他方法類似,可輸出url查看參數是否正確添加:
>>> print(r.url)
http://www.baidu.com/get?key1=value1&key2=value2&key2=value3
需要注意的是,如果參數值是None的話,該參數就不會添加進 url
requests.get(url)返回Response對象,Response對象有一些處理網絡資源的方法:
>>> import requests
>>> r = requests.get('https://api.github.com/events')
>>> r.status_code #獲取返回碼,如請求成功,返回200,失敗,返回404等
>>> r.text #如果不修改編碼,會返回默認編碼格式的文本,適用於文本處理
u'[{"repository":{"open_issues":0,"url":"https://github.com/...
如果要在網頁中查找某些資源鏈接等等,修改網頁源碼編碼後再用text獲得網頁源碼文本,以便於進行文本處理,例如用BeautifulSoup處理
>>> r.encoding #獲取當前網頁編碼格式
'utf-8'
>>> r.encoding = 'ISO-8859-1' #修改當前網頁源碼的格式
>>> r.content #返回字節型格式的文本,適用於內容處理保存
b'[{"repository":{"open_issues":0,"url":"https://github.com/...
例如,需要在網上下載圖片,有一種方法是:通過.get()方法獲取圖片源碼,然後通過.content方法將圖片源碼以字節形式保存到文件中,這樣就能得到圖片。
>>> r = requests.get(‘http://…/xx.jpg’)
f = open(‘D://1.jpg’, ‘wb’)
f.write(r.content)
f.close()
或者:
>>> from PIL import Image
>>> from io import BytesIO
>>> i = Image.open(BytesIO(r.content))
JSON Response Content處理返回資源中的JSON
>>> import requests
>>> r = requests.get('https://api.github.com/events')
>>> r.json()
[{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...
Response對象中的.json()方法可以處理JSON格式的內容,需要注意的是:
如果返回內容中無JSON格式內容,會引發異常,錯誤代碼:204(No Content)
如果返回內容格式不對,會引發值錯誤:ValueError:No JSON object could be decoded
Custom Headers定製請求頭
可通過字典類型的headers參數想url中添加HTTP頭部
>>> url = 'https://api.github.com/some/endpoint'
>>> headers = {'user-agent': 'my-app/0.0.1'}
>>> r = requests.get(url, headers=headers)
注意:header的值必須是字符串、字節串或Unicode類型
More complicated POST requests關於post
post方法也可添加參數:
>>> payload = {'key1': 'value1', 'key2': 'value2'}
>>> r = requests.post("http://httpbin.org/post", data=payload)
>>> print(r.text)
{
...
"form": {
"key2": "value2",
"key1": "value1"
},
...
}
也可以通過內置方法來自動處理json格式的參數:
>>> 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 a Multipart-Encoded File
還可以通過post上傳多種格式的文件:
>>> 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"
},
...
}
Response Status Codes返回狀態碼
前面提到過,可通過.status_code獲取返回碼,用以判斷請求是否成功
>>> r = requests.get('http://httpbin.org/get')
>>> r.status_code
200
#記得404嗎?請求失敗很多時候網頁都會顯示這個
>>> r.status_code == requests.codes.ok
True
當請求可能失敗時,可通過如下方式觸發異常:
>>> 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
但是,當網頁請求成功,返回202時,使用raise_for_status()會返回None
Response Headers 響應頭
獲得返回對象後,可通過.headers方法查看響應頭信息:
>>> r.headers
{
'content-encoding': 'gzip',
'transfer-encoding': 'chunked',
'connection': 'close',
'server': 'nginx/1.0.4',
'x-runtime': '148ms',
'etag': '"e1ca502697e5c9317743dc078f67693f"',
'content-type': 'application/json'
}
HTTP頭信息的名稱是大小寫不敏感的,因此,下面的方法都可以
>>> r.headers['Content-Type']
'application/json'
>>> r.headers.get('content-type')
'application/json
Cookies
獲取Cookies的方法:
>>> url = 'http://example.com/some/cookie/setting/url'
>>> r = requests.get(url)
>>> r.cookies['example_cookie_name']
'example_cookie_value'
制定自己的Cookies併發送給服務器:
>>> url = 'http://httpbin.org/cookies'
>>> cookies = dict(cookies_are='working')
>>> r = requests.get(url, cookies=cookies)
>>> r.text
'{"cookies": {"cookies_are": "working"}}'
返回的Cookies保存在類似於dict格式的RequestsCookieJar中,這個Jar方法有更加豐富的接口。
>>> 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"}}'
Redirection and History 重定向和請求歷史
可以使用history方法追蹤重定向
>>> r = requests.get('http://github.com')
>>> r.url
'https://github.com/'
>>> r.status_code
200
>>> r.history
[<Response [301]>]
在使用GET, OPTIONS, POST, PUT, PATCH or DELETE這些方法時,可以通過allow_redirects參數關閉重定向
>>> r = requests.get('http://github.com', allow_redirects=False)
>>> r.status_code
301
>>> r.history
[]
使用HEAD方法時,也可以通過allow_redirects參數開啟重定向
>>> r = requests.head('http://github.com', allow_redirects=True)
>>> r.url
'https://github.com/'
>>> r.history
[<Response [301]>]
Timeouts 超時
設置請求超時時間,避免程序無線掛起不能繼續執行
>>> 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)
Errors and Exceptions 常見錯誤和異常
網絡異常 —— ConnectionError
請求失敗 —— Response.raise_for_status會引發HTTPError
請求超時 —— Timeout
重定向過多 —— TooManyRedirects