简体   繁体   English

Python 请求无法下载文件

[英]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.我登录网站下载一个 xls 文件,我只是在文件中获得了欢迎站点的乙基代码。 When I open the site in my browser and have a active session the code works perfectly.当我在浏览器中打开该站点并拥有一个活动的 session 时,代码可以完美运行。 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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