Skip to content
Advertisement

Not able to download a file through request in python

When I try to download a file online it doesn’t work for a particular site while it works for others. Why is this happening and what should I do about it?

I write the content of the dl request in my case https://drivers.amd.com/drivers/amd-software-adrenalin-edition-22.11.1-win10-win11-nov15.exe (warning: 500+ MB file) from this page: https://www.amd.com/fr/support/graphics/amd-radeon-6000-series/amd-radeon-6900-series/amd-radeon-rx-6900-xt

headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36'}

web = Session()
web.headers.update(headers)

def dl_btn(self):
        try:
            dl = web.get(self.link) #I use an old session that allowed me to retrieve a download link.
            file = dl.headers['Content-Disposition'].split('=')[1]
            file = filedialog.askdirectory() + '/' + file #Open file explorer to choose the download destination.
            open(file, "wb").write(dl.content)
        except:
            popen(f'start {self.link}') #It open a page that indicate me a wrong request...

Advertisement

Answer

If you read the error page, it tells you exactly what the problem is: they don’t allow downloads without a referer from their website. Therefore, your headers will need to include a Referer key/value, and I assume a proper User-Agent as well:

import requests
from tkinter import filedialog

referer = "https://www.amd.com/fr/support/graphics/amd-radeon-6000-series/amd-radeon-6900-series/amd-radeon-rx-6900-xt"
file_to_dl = "https://drivers.amd.com/drivers/amd-software-adrenalin-edition-22.11.1-win10-win11-nov15.exe"
user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36"
headers = {"User-Agent": user_agent,
           "Referer": referer}

r = requests.get(file_to_dl, headers=headers)
# wait a while...
file = file_to_dl.split("/")[-1]
file_location = filedialog.askdirectory() + '/' + file
open(file_location, "wb").write(r.content)
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement