Python httplib.InvalidURL: odd port rejection

I am trying to open a URL in Python that needs a username and password. My specific implementation is as follows:

http://char_user: char_pwd@casfcddb.example.com /...... 

I get the following error: click

 httplib.InvalidURL: nonnumeric port: ' char_pwd@casfcddb.example.com ' 

I use urllib2.urlopen, but the error implies that he does not understand the user credentials. What he sees is ":" and expects a port number, not a password and an actual address. Any ideas what I'm doing wrong here?

+4
source share
2 answers

Use BasicAuthHandler to provide a password instead:

 import urllib2 passman = urllib2.HTTPPasswordMgrWithDefaultRealm() passman.add_password(None, "http://casfcddb.xxx.com", "char_user", "char_pwd") auth_handler = urllib2.HTTPBasicAuthHandler(passman) opener = urllib2.build_opener(auth_handler) urllib2.install_opener(opener) urllib2.urlopen("http://casfcddb.xxx.com") 

or using the query library:

 import requests requests.get("http://casfcddb.xxx.com", auth=('char_user', 'char_pwd')) 
+8
source

I came across a situation where I needed BasicAuth processing and I only had urllib available (no urllib2 or requests). The answer from Uku basically worked, but here are my mods:

 import urllib.request url = 'https://your/url.xxx' username = 'username' password = 'password' passman = urllib.request.HTTPPasswordMgrWithDefaultRealm() passman.add_password(None, url, username, password) auth_handler = urllib.request.HTTPBasicAuthHandler(passman) opener = urllib.request.build_opener(auth_handler) urllib.request.install_opener(opener) resp = urllib.request.urlopen(url) data = resp.read() 
0
source

Source: https://habr.com/ru/post/1497299/


All Articles