1. 程式人生 > 實用技巧 >requests模組中通用的請求方法,即requests.request

requests模組中通用的請求方法,即requests.request

import requests

1、通用的request請求方法,但是需要多新增一個引數即請求方法,格式為requests.request("請求方法","請求資訊")

# res = requests.get('https://httpbin.org/get')
# res = requests.request('GET', 'https://httpbin.org/get')
#
# res = requests.post('https://httpbin.org/post', data={'a': 1})
# res = requests.request('POST', 'https://httpbin.org/post', data={'a': 1})

2、

①可以將請求資料單獨提取出來,然後傳給共用的requests請求方法,通過for迴圈,來完成不同請求方法的介面,
②字典可用dict(a=b)或者{"a":"b"}兩種方式來表達;
③解包使用**

import requests
# res = requests.request(
#     method='post',   # 也可以只寫'post',
#     url='https://httpbin.org/post',  # 也可以只寫'https://httpbin.org/post',
#     headers={},
#     data={'name': '臨淵', 'password': '123456'}
# )

req1 = dict(
    method='post',   # 也可以只寫'post',
    url='https://httpbin.org/post',  # 也可以只寫'https://httpbin.org/post',
    headers={},
    data={'name': '臨淵', 'password': '123456'}
)

req2 = dict(
    method='get',   # 也可以只寫'get',
    url='https://httpbin.org/get',  # 也可以只寫'https://httpbin.org/post',
    headers={},
)

req_list = [req1, req2]
# req1 = {
#     'method': 'post',
# }

for req in req_list:
    res = requests.request(**req)    #需要通過**來獲取到原始的字典格式資料
    print(res.text)