python requests庫的簡單使用

xie仗劍天涯發表於2017-05-21

requests是python的一個HTTP客戶端庫,跟urllib,urllib2類似,但比urllib,urllib2更加使用簡單。

1. requests庫的安裝
在你的終端中執行pip安裝命令即可

pip install requests

  

使用原始碼安裝

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

  

2. requests傳送請求
使用 Requests 傳送網路請求

import requests

req0 = requests.get("https://www.baidu.com")
print (req0)

  

# 傳送一個 HTTP POST 請求

req1 = requests.post("https://http://httpbin.org/post")

  

# 傳送PUT,DELETE,HEAD 以及 OPTIONS 請求

requests.put("http://http://httpbin.org/put")
requests.delete("http://http://httpbin.org/delete")
requests.head("http://http://httpbin.org/get")
requests.options("http://http://httpbin.org/get")

  


3. 傳遞URL 引數
Requests 使用 params 關鍵字引數,以一個字典來提供這些引數

payload = {'key1': 'value1', 'key2': 'value2'}
req2 = requests.get("https://httpbin.org/get",params=payload)
print (req2.url)
# https://httpbin.org/get?key2=value2&key1=value1

  

# 注:字典裡值為 None 的鍵都不會被新增到 URL 的查詢字串裡

將一個列表作為值傳入

payload = {'key1': 'value1', 'key2': ['value2', 'value3']}
req3 = requests.get('http://httpbin.org/get', params=payload)
print (req3.url)
# http://httpbin.org/get?key2=value2&key2=value3&key1=value1

  


4. 響應內容
requests 讀取伺服器響應的內容

import requests
req4 = requests.get("https://www.baidu.com")
print (req4.text)

  

Requests 會自動解碼來自伺服器的內容。大多數 unicode 字符集都能被無縫地解碼,使用req4.encoding 屬性可以查詢編碼格式和改變編碼型別

>>> req4.encoding
'ISO-8859-1'
>>> req4.encoding = 'utf-8'
>>> req4.encoding
'utf-8'

  

5. 二進位制響應內容
Requests 會自動為你解碼 gzip 和 deflate 傳輸編碼的響應資料

print (req4.content)

  

6. JSON 響應內容
Requests 中也有一個內建的 JSON 解碼器,幫助處理 JSON 資料

import requests
req6 = requests.get("https://github.com/timeline.json")
print (req6.json)

  

# 如果 JSON 解碼失敗, r.json 就會丟擲一個異常。例如,相應內容是 401 (Unauthorized),嘗試訪問 r.json 將會丟擲 ValueError: No JSON object could be decoded 異常

7. 原始響應內容
想獲取來自伺服器的原始套接字響應,可以訪問 r.raw. 不過先要確保在初始請求中設定了 stream=True

req7 = requsets.get('https://github.com/timeline.json',stream = True)
print (req7.raw)
print (req7.raw.read(10))

  

8. 定製請求頭
為請求新增 HTTP 頭部,只要簡單地傳遞一個 dict 給 headers 引數就可以了

url = 'https://api.github.com/some/endpoint'
headers = {'user-agent': 'my-app/0.0.1'}
req8 = requests.get(url, headers=headers)

  

注:注意: 所有的 header 值必須是 string、bytestring 或者 unicode

9. 更加複雜的 POST 請求
傳送一些編碼為表單形式的資料——非常像一個 HTML 表單。要實現這個,只需簡單地傳遞一個字典給 data 引數。資料字典在發出請求時會自動編碼為表單形式

payload = {'key1':'value1','key2':'value2'}
req9 = requests.post("http://httpbin.org/post", data=payload)
print (req9.text)
'''
{
"args": {}, 
"data": "", 
"files": {}, 
"form": {
"key1": "value1", 
"key2": "value2"
}, 
"headers": {
"Accept": "*/*", 
"Accept-Encoding": "gzip, deflate", 
"Connection": "close", 
"Content-Length": "23", 
"Content-Type": "application/x-www-form-urlencoded", 
"Host": "httpbin.org", 
"User-Agent": "python-requests/2.6.0 CPython/2.7.5 Linux/3.10.0-327.36.1.el7.x86_64"
}, 
"json": null, 
"origin": "112.35.10.78", 
"url": "http://httpbin.org/post"
}
'''

  

傳遞一個 string 而不是一個 dict,那麼資料會被直接釋出出去

import json
url = 'https://api.github.com/some/endpoint'
payload = {'some':'data'}
req10 = requests.post(url,data=json.dumps(payload))
print (req10)
# {"message":"Not Found","documentation_url":"https://developer.github.com/v3"}

  

10. POST一個多部分編碼(Multipart-Encoded)的檔案

Requests 使得上傳多部分編碼檔案變得很簡單

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"
},
...
}
'''

  

11. 響應狀態碼
檢測響應狀態碼

req11 = requests.get('http://httpbin.org/get')
req11.status_code
# 200

  

Requests還附帶了一個內建的狀態碼查詢物件

req11.status_code == requests.codes.ok
# True

  

12. 響應頭
檢視以一個 Python 字典形式展示的伺服器響應頭

req11.headers
'''
{'content-length': '311', 'via': '1.1 vegur', 'x-powered-by': 'Flask', 'server': 'meinheld/0.6.1', 'connection': 'keep-alive', 'x-processed-time': '0.000663995742798', 'access-control-allow-credentials': 'true', 'date': 'Fri, 19 May 2017 12:38:25 GMT', 'access-control-allow-origin': '*', 'content-type': 'application/json'}
'''

  


注: 響應頭的字典比較特殊:它是僅為 HTTP 頭部而生的。HTTP 頭部是大小寫不敏感的

13. Cookie
如果響應中包含一些 cookie,你可以快速訪問它們

url = 'http://example.com/some/cookie/setting/url'
req13 = requests.get(url)
req13.cookies['example_cookie_name']
# 'example_cookie_name'

  

傳送你的cookies到伺服器,可以使用 cookies 引數

url = 'http://httpbin.org/cookies'
cookies = dict(cookies_are='working')
req14 = requests.get(url,cookies=cookies)
print (req14.text)
'''
{
"cookies": {
"cookies_are": "working"
}
}
'''

  

14. 重定向與請求歷史
使用響應物件的 history 方法來追蹤重定向
Response.history 是一個 Response 物件的列表,為了完成請求而建立了這些物件。這個物件列表按照從最老到最近的請求進行排序

req15 = requests.get('http://github.com')
print (req15.url)
# https://github.com/
print (req15.status_code)
# 200
print (req15.history)
# [<Response [301]>]

  

如果使用的是GET、OPTIONS、POST、PUT、PATCH 或者 DELETE,那麼可以通過 allow_redirects 引數禁用重定向處理

req16 = requests.get('http://github.com',allow_redirects=False)
print (req16.status_code)
# 301
print (req16.history)
# []

  

使用了 HEAD,可以啟用重定向

req17 = requests.head('http://github.com',allow_redirects=True)
print (req17.url)
# https://github.com/
print (req17.history)
# [<Response [301]>]

  

15. 超時
requests 在經過以 timeout 引數設定的秒數時間之後停止等待響應
注:timeout 僅對連線過程有效,與響應體的下載無關。 timeout 並不是整個下載響應的時間限制,而是如果伺服器在 timeout 秒內沒有應答,將會引發一個異常(更精確地說,是在 timeout 秒內沒有從基礎套接字上接收到任何位元組的資料時)

16. 錯誤與異常
(1) 遇到網路問題(如:DNS 查詢失敗、拒絕連線等)時,Requests 會丟擲一個 ConnectionError 異常。
(2) 如果 HTTP 請求返回了不成功的狀態碼, Response.raise_for_status() 會丟擲一個 HTTPError 異常。
(3) 若請求超時,則丟擲一個 Timeout 異常。
(4) 若請求超過了設定的最大重定向次數,則會丟擲一個 TooManyRedirects 異常。
(5) 所有Requests顯式丟擲的異常都繼承自 requests.exceptions.RequestException 。

 

參考連結:http://docs.python-requests.org/zh_CN/latest/user/quickstart.html

 

相關文章