Download a file from https with authentication

user3262537 picture user3262537 · Feb 13, 2016 · Viewed 27.1k times · Source

I have a Python 2.6 script that downloades a file from a web server. I want this this script to pass a username and password(for authenrication before fetching the file) and I am passing them as part of the url as follows:

import urllib2
response = urllib2.urlopen("http://'user1':'password'@server_name/file")

However, I am getting syntax error in this case. Is this the correct way to go about it? I am pretty new to Python and coding in general. Can anybody help me out? Thanks!

Answer

willnx picture willnx · Feb 13, 2016

If you can use the requests library, it's insanely easy. I'd highly recommend using it if possible:

import requests

url = 'http://somewebsite.org'
user, password = 'bob', 'I love cats'
resp = requests.get(url, auth=(user, password))