[TOC]
<br>
### requests 庫介紹
requests庫宣言:HTTP for Humans (給人用的 HTTP 庫)
它強大,但是卻非常非常的容易使用。也是我們最常用的一個庫。
<center>***`掌握requests,不是應該,是必須...`***</center>
使用requests之前,我們必須要先安裝
```cmd
pip install requests
```
---
### 使用requests發送HTTP請求
```python
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import requests
# 設置請求參數,以字典的key-val形式存儲
payload = {'key1': 'value1', 'key2': 'value2'}
# 設置請求頭信息,以字典的key-val形式存儲
header = {
'User-Agent': 'Mozilla/5.0 (Linux; Android 4.1.1; MI 2 Build/JRO03L) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/37.0.0.0 Mobile MQQBrowser/6.8 TBS/036887 Safari/537.36 MicroMessenger/6.3.27.880 NetType/WIFI Language/zh_CN',
'Cookie': 'TestCookie=PTQA',
'Accept-Encoding': 'gzip',
}
# 使用requests發送一個GET請求
r1 = requests.get("http://httpbin.org/get", params=payload,headers=header)
print("GET請求的響應結果:",r1.text)
# 使用requests發送一個POST請求
r2 = requests.post("http://httpbin.org/post", data=payload,headers=header)
print("POST請求的響應結果:",r2.text)
```
運行結果如:
```cmd
GET請求的響應結果: {"args":{"key1":"value1","key2":"value2"},"headers":{"Accept":"*/*","Accept-Encoding":"gzip","Connection":"close","Cookie":"TestCookie=PTQA","Host":"httpbin.org","User-Agent":"Mozilla/5.0 (Linux; Android 4.1.1; MI 2 Build/JRO03L) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/37.0.0.0 Mobile MQQBrowser/6.8 TBS/036887 Safari/537.36 MicroMessenger/6.3.27.880 NetType/WIFI Language/zh_CN"},"origin":"157.61.158.164","url":"http://httpbin.org/get?key1=value1&key2=value2"}
POST請求的響應結果: {"args":{},"data":"","files":{},"form":{"key1":"value1","key2":"value2"},"headers":{"Accept":"*/*","Accept-Encoding":"gzip","Connection":"close","Content-Length":"23","Content-Type":"application/x-www-form-urlencoded","Cookie":"TestCookie=PTQA","Host":"httpbin.org","User-Agent":"Mozilla/5.0 (Linux; Android 4.1.1; MI 2 Build/JRO03L) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/37.0.0.0 Mobile MQQBrowser/6.8 TBS/036887 Safari/537.36 MicroMessenger/6.3.27.880 NetType/WIFI Language/zh_CN"},"json":null,"origin":"157.61.158.164","url":"http://httpbin.org/post"}
```
請求參數與請求頭,是非必須的,根據具體請求要求確定是否需要。
在python中,通過requests庫發送一個HTTP請求,簡單到不可思議,例如這樣一行代碼`requests.get(url=""http://httpbin.org/get")`就發起了一個GET請求。
---
### 解析Response對象中的屬性
```python
resp = requests.request("GET","http://httpbin.org/get")
```
**主要的屬性**
- ***resp.url***:最終響應的請求地址(當有302重定向時,可不是最初的請求地址哦)
- ***resp.status_code***: HTTP響應碼,如‘404’,‘200’等
- ***resp.headers***:HTTP響應頭信息
- ***resp.history***: 請求歷史記錄列表
- ***resp.encoding***:在訪問r.text 時進行解碼的編碼。
**屬性方法@property**
- ***resp.content***:返回響應內容,字節類型bytes
- ***resp.text***:返回響應內容,unicode類型。編碼格式由r.encoding決定的,在訪問text屬性前,允許我們設定合適的編碼格式。
**常用方法**
- ***resp.json()***:如果響應內容為json字符串,則會轉換為json對象
《實例演示》:
```python
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import requests
# 設置請求參數,以字典的key-val形式存儲
payload = {'key1': 'value1', 'key2': 'value2'}
# 設置請求頭信息,以字典的key-val形式存儲
header = {
'User-Agent': 'Mozilla/5.0 (Linux; Android 4.1.1; MI 2 Build/JRO03L) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/37.0.0.0 Mobile MQQBrowser/6.8 TBS/036887 Safari/537.36 MicroMessenger/6.3.27.880 NetType/WIFI Language/zh_CN',
'Cookie': 'TestCookie=PTQA',
'Accept-Encoding': 'gzip',
}
# 使用requests發送一個POST請求
resp = requests.post("http://postman-echo.com/post", data=payload,headers=header)
print("請求的URL:",resp.url)
print("響應碼:",resp.status_code)
print("響應頭:",resp.headers)
print("響應Cookie:",resp.cookies)
print("請求歷史:",resp.history)
print("響應內容的編碼格式:",resp.encoding)
print("響應內容,字節類型bytes:",resp.content)
print("響應內容,unicode類型:",resp.text)
if resp.headers.get("content-type") == "application/json":
print("響應內容,字典對象:",resp.json())
```
運行結果如下:
```cmd
請求的URL: http://postman-echo.com/post
響應碼: 200
響應頭: {'Content-Encoding': 'gzip', 'Content-Type': 'application/json; charset=utf-8', 'Date': 'Mon, 23 Jul 2018 13:53:47 GMT', 'ETag': 'W/"269-dp22/aBwvg6BLnokGzBSy+I+NSA"', 'Server': 'nginx', 'set-cookie': 'sails.sid=s%3AYcCxFgX3kgNdGk90nI37fFo4CV782M8U.rlE4FEN%2B9SKrbKIN9LMmouHjmT2TipR8mmdRUwjK%2FDs; Path=/; HttpOnly', 'Vary': 'Accept-Encoding', 'Content-Length': '416', 'Connection': 'keep-alive'}
響應Cookie: <RequestsCookieJar[<Cookie sails.sid=s%3AYcCxFgX3kgNdGk90nI37fFo4CV782M8U.rlE4FEN%2B9SKrbKIN9LMmouHjmT2TipR8mmdRUwjK%2FDs for postman-echo.com/>]>
請求歷史: []
響應內容的編碼格式: utf-8
響應內容,字節類型bytes: b'{"args":{},"data":"","files":{},"form":{"key1":"value1","key2":"value2"},"headers":{"host":"postman-echo.com","content-length":"23","accept":"*/*","accept-encoding":"gzip","content-type":"application/x-www-form-urlencoded","cookie":"TestCookie=PTQA","user-agent":"Mozilla/5.0 (Linux; Android 4.1.1; MI 2 Build/JRO03L) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/37.0.0.0 Mobile MQQBrowser/6.8 TBS/036887 Safari/537.36 MicroMessenger/6.3.27.880 NetType/WIFI Language/zh_CN","x-forwarded-port":"80","x-forwarded-proto":"http"},"json":{"key1":"value1","key2":"value2"},"url":"http://postman-echo.com/post"}'
響應內容,unicode類型: {"args":{},"data":"","files":{},"form":{"key1":"value1","key2":"value2"},"headers":{"host":"postman-echo.com","content-length":"23","accept":"*/*","accept-encoding":"gzip","content-type":"application/x-www-form-urlencoded","cookie":"TestCookie=PTQA","user-agent":"Mozilla/5.0 (Linux; Android 4.1.1; MI 2 Build/JRO03L) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/37.0.0.0 Mobile MQQBrowser/6.8 TBS/036887 Safari/537.36 MicroMessenger/6.3.27.880 NetType/WIFI Language/zh_CN","x-forwarded-port":"80","x-forwarded-proto":"http"},"json":{"key1":"value1","key2":"value2"},"url":"http://postman-echo.com/post"}
```
---
### 保持會話狀態
由于HTTP的無狀態特性,若不借助其他手段,遠程的服務器就無法知道以前和客戶端做了哪些通信。Cookie就是「其他手段」之一。
Cookie 一個典型的應用場景,就是用于記錄用戶在網站上的登錄狀態。
1.用戶登錄成功后,服務器下發一個(通常是加密了的)Cookie 文件。
2.客戶端(通常是網頁瀏覽器)將收到的 Cookie 文件保存起來。
3.下次客戶端與服務器連接時,將 Cookie 文件發送給服務器,由服務器校驗其含義,恢復登錄狀態(從而避免再次登錄)
#### 方式一:在請求中手工添加Cookie參數
```python
import requests
# cookie通過requests的cookies參數傳遞
r1 = requests.get("http://httpbin.org/cookies", cookies={"is_login": "True"})
# cookie通過headers參數傳遞
r2 = requests.get("http://httpbin.org/cookies", headers={'cookie': 'is_login=True'})
print(r1.text)
print(r2.text)
```
運行結果如:
```cmd
{"cookies":{"is_login":"True"}}
{"cookies":{"is_login":"True"}}
```
同時存在headers和cookies參數時,headers中的cookie會覆蓋cookies參數中的cookie
#### 方式二:使用Session自動攜帶Cookie
session會自動管理cookie,一個session對象會保持同一個會話中的所有請求之間的cookie信息。
```python
import requests
r1 = requests.post("https://postman-echo.com/response-headers?foo1=bar1&foo2=bar2")
print("request第一次響應cookie:",r1.cookies)
r2 = requests.post("https://postman-echo.com/response-headers?foo1=bar1&foo2=bar2")
print("request第二次請求cookie:",r2.request._cookies)
# print()
print("")
#創建Session實例
s = requests.Session()
r3 = s.post("https://postman-echo.com/response-headers?foo1=bar1&foo2=bar2")
print("session第一次響應cookie:",r3.cookies)
r4 = s.post("https://postman-echo.com/response-headers?foo1=bar1&foo2=bar2")
print("session第二次請求cookie:",r4.request._cookies)
```
運行結果如:
```cmd
request第一次響應cookie: <RequestsCookieJar[<Cookie sails.sid=s%3A6Ea1SO0RWIZKed43fQhhRVSvpBURT0h0.7xmVIYhg7xaqMpCpcJk7SlTFTg5bm4MY4eRjIuAm5L8 for postman-echo.com/>]>
request第二次請求cookie: <RequestsCookieJar[]>
session第一次響應cookie: <RequestsCookieJar[<Cookie sails.sid=s%3A60M5buOIVPZIAaBfuNaR3a0s3Q9ExQpK.uYhz9%2B1ZE5O4Hb8qUTCquf4w7af3CynDWNXJjQ9rGko for postman-echo.com/>]>
session第二次請求cookie: <RequestsCookieJar[<Cookie sails.sid=s%3A60M5buOIVPZIAaBfuNaR3a0s3Q9ExQpK.uYhz9%2B1ZE5O4Hb8qUTCquf4w7af3CynDWNXJjQ9rGko for postman-echo.com/>]>
```
通過以上結果對比可知,一個session對象會保持同一個會話中的所有請求之間的cookie信息。
---
### requests.request 中那些重要的參數
如果你認真觀看本書,當你讀到這里的時候,應該體會到`源碼才是最好的文檔`。
通過閱讀源碼,我們可以看到request的參數有很多,這里不一一講解,只強調其中兩個比較重要的三個參數:timeout,allow_redirects,verify
#### 設置超時時間 timeout
為防止服務器不能及時響應,大部分發至外部服務器的請求都應該帶著 timeout 參數。如果沒有 timeout,你的代碼可能會掛起若干分鐘甚至更長時間。
```python
r = requests.get('http://httpbin.org/get', timeout=5)
```
#### 進行SSL證書驗證 verify
默認情況下, verify 是設置為 True 的,如果SSL認證失敗,可以嘗試將verify驗證關閉,verify=False
```python
r = requests.get('https://github.com', verify=True)
```
#### 重定向設置 allow_redirects
默認情況下,allow_redirects 是設置為True的,如果遇到301,302重定向,會自動跳轉。如果我們不想讓其自動跳轉,可以設置 allow_redirects=False
```python
import requests
r1 = requests.get("http://cnblogs.com/")
print("allow_redirects=True時的響應history:",r1.history)
print("allow_redirects=True時的響應url:",r1.url)
print("")
r2 = requests.get("http://cnblogs.com/",allow_redirects=False)
print("allow_redirects=False時的響應history:",r2.history)
print("allow_redirects=False時的響應url:",r2.url)
```
運行結果如下:
```cmd
allow_redirects=True時的響應history: [<Response [301]>, <Response [301]>]
allow_redirects=True時的響應url: https://www.cnblogs.com/
allow_redirects=False時的響應history: []
allow_redirects=False時的響應url: http://cnblogs.com/
```
<hr style="margin-top:100px">
:-: 
***微信掃一掃,關注“python測試開發圈”,了解更多測試教程!***
- 前言
- chapter01_開發環境
- chapter02_字符串的使用
- chapter03_列表的使用
- chapter04_字典的使用
- chapter05_數字的使用
- chapter06_元組的使用
- chapter07_集合的使用
- chapter08_輸入輸出
- chapter09_控制流程
- chapter10_實例練習_登錄1
- chapter11_python函數入門
- chapter12_python中的類
- chapter13_輕松玩轉python中的模塊管理
- chapter14_掌握學習新模塊的技巧
- chapter15_通過os模塊與操作系統交互
- chapter16_子進程相關模塊(subprocess)
- chapter17_時間相關模塊(time & datetime)
- chapter18_序列化模塊(json)
- chapter19_加密模塊(hashlib)
- chapter20_文件的讀與寫
- chapter21_階段考核2_登錄
- chapter22_小小算法挑戰(排序&二分法)
- chapter23_用多線程來搞事!
- chapter24_HTTP接口請求(requests)
- chapter25_接口測試框架(pytest)
- chapter26_階段考核3_HTTP接口測試
- chapter27_HTML解析(pyquery)
- chapter28_階段考核4_爬蟲下載網易汽車
- chapter29_python中的那些編碼坑
- chapter30_MySQL數據庫操作
- chapter31 高級特性_迭代器與生成器
- chapter32 高級特性_裝飾器
- chapter33 高級特性_列表處理