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')

 

posted @ 2019-10-15 20:51  邹邹很busy。  阅读(936)  评论(0编辑  收藏  举报