Skip to main content
 首页 » 编程设计

Python3,通过单击按钮从url下载文件

2025年01月19日10softidea

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

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

请您参考如下方法:

通过添加适当的 header 和使用 session ,我们可以使用请求模块下载和保存文件。

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)