python 使用requests发送POST请求

简介: python 使用requests发送POST请求

一、定义

  • post()方法将携带某些数据的POST请求发送到指定的URL

二、应用场景

  1. 提交表单所涉及到的增删改操作。
  2. 调用API,例如百度云的文字识别接口、阿里云的常用支付接口,都需要用POST请求。
  3. 发送/上传图片、音视频等文件资源。

三、使用方法

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)
相关文章
|
3月前
|
存储 Web App开发 前端开发
Python + Requests库爬取动态Ajax分页数据
Python + Requests库爬取动态Ajax分页数据
|
3月前
|
Web App开发 安全 数据安全/隐私保护
利用Python+Requests实现抖音无水印视频下载
利用Python+Requests实现抖音无水印视频下载
|
28天前
|
数据采集 Web App开发 前端开发
处理动态Token:Python爬虫应对AJAX授权请求的策略
处理动态Token:Python爬虫应对AJAX授权请求的策略
|
3月前
|
JSON 网络安全 数据格式
Python网络请求库requests使用详述
总结来说,`requests`库非常适用于需要快速、简易、可靠进行HTTP请求的应用场景,它的简洁性让开发者避免繁琐的网络代码而专注于交互逻辑本身。通过上述方式,你可以利用 `requests`处理大部分常见的HTTP请求需求。
330 51
|
2月前
|
JSON JavaScript API
Python模拟HTTP请求实现APP自动签到
Python模拟HTTP请求实现APP自动签到
|
3月前
|
数据采集 API 调度
Python爬虫框架对比:Scrapy vs Requests在API调用中的应用
本文对比了 Python 中 Scrapy 与 Requests 两大爬虫框架在 API 调用中的差异,涵盖架构设计、调用模式、性能优化及适用场景,并提供实战建议,助力开发者根据项目需求选择合适工具。
|
28天前
|
数据采集 机器学习/深度学习 人工智能
Python:现代编程的首选语言
Python:现代编程的首选语言
194 102
|
28天前
|
数据采集 机器学习/深度学习 算法框架/工具
Python:现代编程的瑞士军刀
Python:现代编程的瑞士军刀
205 104
|
28天前
|
人工智能 自然语言处理 算法框架/工具
Python:现代编程的首选语言
Python:现代编程的首选语言
187 103

推荐镜像

更多