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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM