
开始了!
发送表单数据并携带文件和字段发送https请求, 无论在后端开发和爬虫开发中都是比较常见的。这篇使用Python中两个常用的HTTP库 aiohttp和 requests 来举例实现。
用例:
aiohttp
aiohttp是一个基于异步的HTTP客户端/服务器框架,在异步程序中比较常用。
安装
官方地址
https://docs.aiohttp.org/en/stable/
示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| # -*- coding: utf-8 -*- # @Author: 胖胖很瘦 # @Date: 2024-03-15 15:56:39 # @LastEditors: 胖胖很瘦 # @LastEditTime: 2024-03-15 15:58:14 import asyncio import aiohttp async def start(url, data, file_path): """ http请求 :param url: 请求地址 :param data: 表单数据 :param file_path: 文件路径 """ async with aiohttp.ClientSession() as session: dataFrom = aiohttp.FormData(data) with open(file_path, 'rb') as file: dataFrom.add_field('file', file, filename=file_path) async with session.post(url, data=data) as response: if response.status == 200: print("请求成功") else: print("请求失败") if __name__ == "__main__": url = 'http://example.com/upload' file_path = 'example.txt' data = {'field1': 'value1', 'field2': 'value2'} asyncio.run(start(url, data, file_path))
|

requests:
requests是一个同步的HTTP库, 在爬虫应用中requests排第二就没有模块排第一。可以使用loop.run_in_executor改为异步运行
官方地址
https://requests.readthedocs.io/en/latest/
示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| # -*- coding: utf-8 -*- # @Author: 胖胖很瘦 # @Date: 2024-03-15 15:56:39 # @LastEditors: 胖胖很瘦 # @LastEditTime: 2024-03-15 15:58:14 import requests import asyncio def start(url, data, file_path): """ http请求 :param url: 请求地址 :param data: 表单数据 :param file_path: 文件路径 """ try: files = {'file': open(file_path, 'rb')} response = requests.post(url, files=files, data=data) if response.status_code == 200: print("请求成功") else: print("请求失败") except Exception as e: print(e) if __name__ == "__main__": url = 'http://example.com/upload' file_path = 'example.txt' data = {'field1': 'value1', 'field2': 'value2'} # 异步请求 loop = asyncio.get_event_loop() loop.run_in_executor(None, start, url, data, file_path) # 同步请求 # start(url, data, file_path)
|
完事了~
在本文中,介绍了如何使用aiohttp和requests库发送表单数据,携带文件和字段的POST请求。aiohttp适用于异步环境,提供更好的性能和扩展性,而requests是同步的,不适用于异步操作,但是可以通过run_in_executor方法在异步环境中使用。选择适合您项目需求的库,并根据需要发送表单数据,携带文件和字段的请求。
差点忘了, 各位周末愉快~
一直在努力, 记得点个在看哦!