简体   繁体   中英

Python Requests can't download file

My Code:

from fake_useragent import UserAgent


ua = UserAgent()

headers = {'Connection': 'keep-alive','User-Agent': str(ua.chrome)}

data = {'inUserName': 'username', 'inUserPass': 'password'}
    
site_url = 'https://www.website.com/home/welcome'

s = requests.Session()
r = s.post(site_url,data=data,headers=headers)

if response.status_code == 200:
        r = s.get("https://www.website.com/text/2017?y=2021&x=xls", allow_redirects=True, headers=headers,cookies=r.cookies)
       
        output = open('file.xls', 'wb')
        output.write(r.content)
        output.close()

Ihn I log into the website to download a xls file i just get th ethyl code of the welcome site in the file. When I open the site in my browser and have a active session the code works perfectly. Does anybody know what to do?

Thanks

You should try this download code

def download_image_from_url(image_url, path):
    img_data = requests.get(image_url).content

    with open(path, 'wb') as handler:
        handler.write(img_data)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM