1. 程式人生 > >python的requests模塊

python的requests模塊

-type params status clas art 請求 let epo ext

使用python進行接口測試得時候可以使用requests模塊,是基於 urllib,采用 Apache2 Licensed 開源協議的 HTTP 庫

安裝requests是模塊

pip install requests

requests模塊的使用

requests支持http的請求類型,如get,post,delete,put,head等

如:

r=requests.get("www.baidu.com")

r=requests.post("www.baidu.com")

傳遞參數

將參數定義為字典類型進行傳遞給params或者data

如,

para={"kw":"python"}

r=reuqests.get{"www.baidu.com",params=para}

字典中值為none的鍵值對不對傳遞過去,字典的值也可以為列表

響應結果

使用r.text獲取到響應結果

json響應結果

使用r.json獲取到json響應結果

二進制響應結果

使用r.content獲取

定制head頭

將定制的head定義為字典類型傳遞給headers即可

head={"content-type":"application/json"}

r.requests.get{‘www.baidu.com‘,params=para,headers=head}

post一個多部分編碼的文件(Multipart-Encoded)

url = ‘http://httpbin.org/post‘
files = {‘file‘: open(‘report.xls‘, ‘rb‘)}

r = requests.post(url, files=files)

如果你發送一個非常大的文件作為 multipart/form-data 請求,你可能希望流請求(?)。默認下 requests 不支持, 但有個第三方包支持 - requests-toolbelt.

安裝

pip install requests-toolbelt

應用

from requests_toolbelt import MultipartEncoder
import requests

m = MultipartEncoder(
    fields={‘field0‘: ‘value‘, ‘field1‘: ‘value‘,
            ‘field2‘: (‘filename‘, open(‘file.py‘, ‘rb‘), ‘text/plain‘)}
    )

r = requests.post(‘http://httpbin.org/post‘, data=m,
                  headers={‘Content-Type‘: m.content_type})

響應嗎

r.status_code

響應頭

r.headers

python的requests模塊