Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Python 3.x snippet code for Basic Authentication HTTP request by urllib.request
#!/usr/bin/env python
# I tested by Python 3.4.3 on Windows 8.1
# Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:43:06) [MSC v.1600 32 bit (Intel)] on win32
import urllib.request
import getpass
# If you access to url below via Proxy,
# set environment variable 'http_proxy' before execute this.
# And, url scheme is https, then 'https_proxy' must be set instead of 'http_proxy'
url = ''
auth_user=input('Username: ')
auth_passwd=getpass.getpass('Password: ')
# If you would like to request Authorization header for Digest Authentication,
# replace HTTPBasicAuthHandler object to HTTPDigestAuthHandler
passman = urllib.request.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, url, auth_user, auth_passwd)
authhandler = urllib.request.HTTPBasicAuthHandler(passman)
opener = urllib.request.build_opener(authhandler)
# I can get http.client.HTTPResponse object in variable 'res'
# ToDo: Error Handling
res = urllib.request.urlopen(url)
res_body =
Copy link

r01shiva commented Jun 24, 2019

I don't know how to express my happiness. I was working on it for 3 days and I didn't find anything which helpful but it is really amazing and its worked. Thanks Man

Copy link

realrains commented Apr 14, 2022

Thanks. I'd look for how to request with auth by only built-in package.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment