Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

connect to url in python

i am trying to connect to a url with a username and password with the following code:

urllib.request.urlopen("http://username:[email protected]...", None)

but i'm getting

urllib.error.URLError: urlopen error [Errno 11003] getaddrinfo failed

anyone know what's up?

like image 911
rach Avatar asked Feb 25 '23 09:02

rach


1 Answers

I'm sorry. I didn't notice you are using py3k.
See urllib.request - FancyURLopener. I personally don't know py3k very well.
Basically, you need to subclass urllib.request.FancyURLopener, override prompt_user_passwd(host, realm), and then call YourClass.urlopen(url).

Below is for py2

This is what you want, urllib2 - Basic Authentication
Below is the code from that page, just in case some day the link rot.

# create a password manager
password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()

# Add the username and password.
# If we knew the realm, we could use it instead of None.
top_level_url = "http://example.com/foo/"
password_mgr.add_password(None, top_level_url, username, password)

handler = urllib2.HTTPBasicAuthHandler(password_mgr)

# create "opener" (OpenerDirector instance)
opener = urllib2.build_opener(handler)

# use the opener to fetch a URL
opener.open(a_url)

# Install the opener.
# Now all calls to urllib2.urlopen use our opener.
urllib2.install_opener(opener)
like image 187
Haozhun Avatar answered Mar 07 '23 22:03

Haozhun