一、定义
- post()方法将携带某些数据的POST请求发送到指定的URL
二、应用场景
- 提交表单所涉及到的增删改操作。
- 调用API,例如百度云的文字识别接口、阿里云的常用支付接口,都需要用POST请求。
- 发送/上传图片、音视频等文件资源。
三、使用方法
1)导入模块
importrequests
2)封装数据
将要发送的数据封装到data中,封装形式可以是字典、json、元组等。
# 发送字典post_dict= {'key1': 'value1', 'key2': 'value2'} # 发送元组post_tuple= (('key1', 'value1'), ('key1', 'value2')) # 发送jsonpost_json=json.dumps({'some': 'data'}) r1=requests.post("http://httpbin.org/post", data=post_dict) r2=requests.post("http://httpbin.org/post", data=post_tuple) r3=requests.post("http://httpbin.org/post", data=post_json)
3)定制header头和cookie信息
cookie="token=code_space;"header= { "cookie": cookie, "Accept": "*/*", "Accept-Encoding": "gzip, deflate, br", "Accept-Language": "zh-CN,zh;q=0.9", "Connection": "keep-alive", "Content-Type": "application/json", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) ""AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36"}
四、测试demo
# -*- coding: utf-8 -*-"""@Time : 2022/1/18 11:36@Auth : 技术空间@File :post_demo.py@IDE :PyCharm@Motto:技术总是要日积月累的"""importrequestsimportjsonif__name__=='__main__': cookie="token=code_space;"header= { "cookie": cookie, "Accept": "*/*", "Accept-Encoding": "gzip, deflate, br", "Accept-Language": "zh-CN,zh;q=0.9", "Connection": "keep-alive", "Content-Type": "application/json", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36" } # 发送字典post_dict= {'key1': 'value1', 'key2': 'value2'} # 发送元组post_tuple= (('key1', 'value1'), ('key1', 'value2')) # 发送jsonpost_json=json.dumps({'some': 'data'}) r1=requests.post("http://httpbin.org/post", data=post_dict, headers=header, cookie=cookie) r2=requests.post("http://httpbin.org/post", data=post_tuple, headers=header, cookie=cookie) r3=requests.post("http://httpbin.org/post", data=post_json, headers=header, cookie=cookie) print("r1返回的内容为-->"+r1.text) print("r2返回的内容为-->"+r2.text) print("r3返回的内容为-->"+r3.text)