Python3,通过单击按钮从URL下载文件 [英] Python3, download file from url by button click

查看:158
本文介绍了Python3,通过单击按钮从URL下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从这样的链接下载文件 https://freemidi.org/getter-13560

I need to download file from link like this https://freemidi.org/getter-13560

但是我不能使用urllib.requestrequests库,因为它下载的是html,而不是midi.有什么解决办法吗?这也是按钮本身的链接链接

But I cant use urllib.request or requests library cause it downloads html, not midi. Is there is any solution? And also here is the link with the button itself link

推荐答案

通过添加适当的标头并使用会话,我们可以使用请求模块下载并保存文件.

By adding the proper headers and using session we can download and save the file using request module.

import requests

headers = {
            "Host": "freemidi.org",
            "Connection": "keep-alive",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36",
            "Accept-Encoding": "gzip, deflate, br",
            "Accept-Language": "en-US,en;q=0.9",
           }

session = requests.Session()

#the website sets the cookies first
req1 = session.get("https://freemidi.org/getter-13560", headers = headers)

#Request again to download
req2 = session.get("https://freemidi.org/getter-13560", headers = headers)
print(len(req2.text))     # This is the size of the mdi file

with open("testFile.mid", "wb") as saveMidi:
    saveMidi.write(req2.content)

这篇关于Python3,通过单击按钮从URL下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆