I found some python code on the web to download an attachment from a website (eg an excel or pdf file). This code works perfectly. Except when the weblink to download a file shows aspx or asph. The following code snippet works. However when I change the variable called url below with a link with aspx or ashx in it then it does not download. Eg if I replace by url = 'https://kingcounty.gov/~/media/depts/health/communicable-diseases/documents/C19/data/vax_public.ashx?la=en'
How do I fix this?
import requests
print('Download Starting...')
url = 'http://www.tutorialspoint.com/python3/python_tutorial.pdf'
r = requests.get(url)
filename = url.split('/')[-1] # this will take only -1 splitted part of the url
with open(filename,'wb') as output_file:
output_file.write(r.content)
print('Download Completed!!!')
In your code filename = url.split('/')[-1]
is right for http://www.tutorialspoint.com/python3/python_tutorial.pdf
But filename = url.split('/')[-1]
is not suitable for https://kingcounty.gov/~/media/depts/health/communicable-diseases/documents/C19/data/vax_public.ashx?la=en
So change the filename syntax. Take a filename in a string with a file extension like
filename = 'filename.xlsx'
import requests
print('Download Starting...')
url = 'https://kingcounty.gov/~/media/depts/health/communicable-diseases/documents/C19/data/vax_public.ashx?la=en'
r = requests.get(url)
filename = 'filename.xlsx'
with open(filename, 'wb') as output_file:
output_file.write(r.content)
print('Download Completed!!!')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.