python接口测试之requests详解_Python接口测试-requests库
一、requests庫
Requests 是用Python語言編寫,基于 urllib,采用 Apache2 Licensed 開源協議的 HTTP 庫。它比 urllib 更加方便,可以節約我們大量的工作,完全滿足 HTTP 測試需求。
二、發請求
response = requests.get(‘https://github.com/timeline.json’) #GET請求
response = requests.post(“http://httpbin.org/post”) #POST請求
response = requests.put(“http://httpbin.org/put”) #PUT請求
response = requests.delete(“http://httpbin.org/delete”) #DELETE請求
response = requests.head(“http://httpbin.org/get”) #HEAD請求
response = requests.options(“http://httpbin.org/get”) #OPTIONS請求
返回類型是一個HTTPresponse類型。
print(response.status_code) # 打印狀態碼
print(response.url) # 打印請求url
print(response.headers) # 打印頭信息
print(response.cookies) # 打印cookie信息
print(response.text) #以文本形式打印網頁源碼
print(response.content) #以字節流形式打印
三、傳參
1、方法
(1)直接將參數放在url內
response = requests.get(http://httpbin.org/get?name=gemey&age=22)
(2)先將參數填寫在dict中,發起請求時params參數指定為dict
data = {
'name': 'tom',
'age': 20
}
response = requests.get('http://httpbin.org/get', params=data)
2、為你的請求添加頭信息
heads = {}
heads['User-Agent'] = 'Mozilla/5.0 ' \
'(Macintosh; U; Intel Mac OS X 10_6_8; en-us) AppleWebKit/534.50 ' \
'(KHTML, like Gecko) Version/5.1 Safari/534.50'
response = requests.get('http://www.baidu.com',headers=headers)
3、使用代理
proxy = {
'http': '120.25.253.234:812',
'https' '163.125.222.244:8123'
}
req = requests.get(url,proxies=proxy)
4、不同于get請求,post請求可以在body里添加內容
data = {'name':'tom','age':'22'}
response = requests.post('http://httpbin.org/post', data=data)
5、異常捕獲處理
import requests
from requests.exceptions import ReadTimeout,HTTPError,RequestException
try:
response = requests.get('http://www.baidu.com',timeout=0.5)
print(response.status_code)
except ReadTimeout:
print('timeout')
except HTTPError:
print('httperror')
except RequestException:
print('reqerror')
四、會話保持
會話對象讓你能夠跨請求保持某些參數。它也會在同一個 Session 實例發出的所有請求之間保持 cookie。
session = requests.Session()
session.get('http://httpbin.org/cookies/set/number/12345')
response = session.get('http://httpbin.org/cookies')
五、查看和發送Cookie
具體見
requests官方中文文檔
快速入門版?http://docs.python-requests.org/zh_CN/latest/user/quickstart.html
進階版?http://docs.python-requests.org/zh_CN/latest/user/advanced.html#advanced
總結
以上是生活随笔為你收集整理的python接口测试之requests详解_Python接口测试-requests库的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: centos下svn与mysql_cen
- 下一篇: 蜂糖的功效与作用、禁忌和食用方法