Python3, download file from url by button click

2019-07-16 16:00发布

问题:

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

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

回答1:

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)