How to use urllib with username/password authentication in python 3?

Solution 1:

Thankfully to you guys I finally figured out the way it works. Here is my code:

request = urllib.request.Request('http://mysite/admin/index.cgi?index=127')
base64string = base64.b64encode(bytes('%s:%s' % ('login', 'password'),'ascii'))
request.add_header("Authorization", "Basic %s" % base64string.decode('utf-8'))
result = urllib.request.urlopen(request)
resulttext = result.read()

After all, there is one more difference with urllib: the resulttext variable in my case had the type of <bytes> instead of <str>, so to do something with text inside it I had to decode it:

text = resulttext.decode(encoding='utf-8',errors='ignore')

Solution 2:

What about urllib.request ? It seems it has everything you need.

import base64
import urllib.request

request = urllib.request.Request('http://mysite/admin/index.cgi?index=127')
base64string =  bytes('%s:%s' % ('login', 'password'), 'ascii')
request.add_header("Authorization", "Basic %s" % base64string)
result = urllib.request.urlopen(request)
resulttext = result.read()