requests--文件上传,文件下载
文件上传
在做接口自动化的时候,有时需要上传文件,比如更改头像等等,在request里,通过files参数来上传
import requests base_url = 'http://httpbin.org' file = {'file': open(r'E:\00.jpg', 'rb')} r = requests.post(base_url + '/post', files=file)
print(r.text)
文件下载
第一种方式
import requests def dowload_file(file_path): headers = {"Referer": "https://xx315.xx315.nex"} cookie = {"Cookie": "ASP.NET_SessionId=bij"} r = requests.get(url='https://xx315.xx315', cookies=cookie, headers=headers, stream=True) if r.status_code == 200: with open(file_path, 'wb') as f: for chunk in r.iter_content(chunk_size=1024): f.write(chunk) dowload_file('F:\\123.xlsx')
注意:
文件如果不存在,会在当前目录下生成一个文件,有内容会清空在写入
第二种方式
import requests import shutil def download_file_raw(file_path): url = 'https://xx315.xx315.net/Ashx/Export' cookie = {"Cookie": 'ASP.NET_SessionId=sjl8'} r = requests.get(url=url, cookies=cookie, stream=True ) if r.status_code == 200: with open(file_path, 'wb') as f: r.raw.decode_content = True shutil.copyfileobj(r.raw, f) download_file_raw('F:\\123.xlsx')
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)