在接口请求参数中,Form Data算是相对少见的,也正是少见,所以平时并没有太留意用法,有一些细节处理不好就会容易“上坑”。这里用一个例子简单记录一下用requests发送Form Data的实用例子。
如下图是在抓包过程中看到网络请求Form Data数据格式:
要实现的api接口:
api接口请求发送的数据:
实现的过程主要分2步,需要用到一个第三方模块requests_toolbelt:
1、安装 requests_toolbelt 模块,引入该模块下的 MultipartEncoder封装Form Data
2、生成请求header的centent_type值,并在接口中传入封装好的Form Data参数对象。
如下实现代码:
"""
@IDE: PyCharm
@Desc:
"""
from requests_toolbelt.multipart.encoder import MultipartEncoder
import requests
headers = {
"Accept": "*/*",
"Accept-Language": "zh-CN,zh;q=0.9",
"Cache-Control": "no-cache",
"Connection": "keep-alive",
"Content-Type": "multipart/form-data; boundary=----WebKitFormBoundary6zQNxu3pk2G0HUKs",
"Origin": "https://为安全着想,此处具体值省略",
"Pragma": "no-cache",
"Referer": "https://为安全着想,此处具体值省略-campaigns?ref_=vc_xx_subNav",
"Sec-Fetch-Dest": "empty",
"Sec-Fetch-Mode": "cors",
"Sec-Fetch-Site": "same-origin",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36",
"X-Requested-With": "XMLHttpRequest",
"cookie":'''为安全着想,此处具体值省略'''
}
request_body = MultipartEncoder(
{
"coupon-campaign-search-name":"",
"coupon-campaign-search-date-option":"range",
"coupon-campaign-search-start-date":"1/4/2022",
"coupon-campaign-search-end-date":"",
"coupon-campaign-search-budget-type":"all",
"coupon-campaign-search-campaign-status":"all",
"anti-csrftoken-a2z":"hD03rdqaG8lSAPNsKztlOCfqcgOBjiFLO5e2g/qmG7tmAAAAAGJktrEAAAAB"}
)
headers['Content-Type']= request_body.content_type
res = requests.post(
"https://为安全着想,此处具体值省略/ajax/campaigns-search",
headers=headers,
data=request_body,
)
print(res.text)
print(len(res.text),res.status_code)