开发者

Read https url from Python with basic access authentication

开发者 https://www.devze.com 2022-12-13 21:50 出处:网络
How do you open https url in Python? import urllib2 url = \"https://user:password@domain.com/path/ f = urllib2.urlopen(开发者_如何学JAVAurl)

How do you open https url in Python?

import urllib2

url = "https://user:password@domain.com/path/
f = urllib2.urlopen(开发者_如何学JAVAurl)
print f.read()

gives:

httplib.InvalidURL: nonnumeric port: 'password@domain.com'


This has never failed me

import urllib2, base64
username = 'foo'
password = 'bar'
auth_encoded = base64.encodestring('%s:%s' % (username, password))[:-1]

req = urllib2.Request('https://somewebsite.com')
req.add_header('Authorization', 'Basic %s' % auth_encoded)
try:
    response = urllib2.urlopen(req)
except urllib2.HTTPError, http_e:
    # etc...
    pass


Please read about the urllib2 password manager and the basic authentication handler as well as the digest authentication handler.

http://docs.python.org/library/urllib2.html#abstractbasicauthhandler-objects

http://docs.python.org/library/urllib2.html#httpdigestauthhandler-objects

Your urllib2 script must actually provide enough information to do HTTP authentication. Usernames, Passwords, Domains, etc.


If you want to pass username and password information to urllib2 you'll need to use an HTTPBasicAuthHandler.

Here's a tutorial showing you how to do it.


You cannot pass credentials to urllib2.open like that. In your case, user is interpreted as the domain name, while password@domain.com is interpreted as the port number.

0

精彩评论

暂无评论...
验证码 换一张
取 消