Answer the question
In order to leave comments, you need to log in
How to implement file upload with basic http authorization in python 3?
Hello
, I have the following problem: I need to download a file from the http server by url, but it is under http basic auth.
If I use a browser to follow a link like this:
http://'login':'pass'@moyserver.com/file.file
The file is downloaded, if in the script:
import urllib.request
serv = 'мой сервер'
Username = 'логин'
Password = 'пароль'
file='полный адрес файла(с директорией)'
site='http://'+Username+':'+Password+'@'+serv+file
n=file.split('/')#Не уверен что красиво, но позволяет быстро отделить имя файла
file=n[-1]
def load(filename,site):
with urllib.request.urlopen(site) as url:
s = url.read()
f = open(filename, "wb")
f.write(s)
f.close()
load(file,site)
Answer the question
In order to leave comments, you need to log in
Very simple
request = Request("http://your_site.ru")
auth = b64encode(bytes("user:password", "ascii")).decode("ascii")
request.add_header("Authorization", "Basic %s" % auth)
response = urlopen(request)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question