2009-12-15 49 views
4

如何在Python中打開https url?使用基本訪問驗證從Python讀取https url

import urllib2 

url = "https://user:[email protected]/path/ 
f = urllib2.urlopen(url) 
print f.read() 

給出:

httplib.InvalidURL: nonnumeric port: '[email protected]' 
+0

的方式來閱讀HTTPS URL在Python是實際*搜索*計算器張貼這已經被問同樣的問題之前。以下是搜索結果:http://stackoverflow.com/search?q=%5Bpython%5D+https – 2009-12-15 12:07:49

回答

2

您不能傳遞憑據urllib2.open這樣。在你的情況下,user被解釋爲域名,而[email protected]被解釋爲端口號。

11

這從來沒有讓我失望

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 
+0

'request.add_header('Authorization',b'Basic'+ base64.b64encode(username + b':'+ password ))' – jfs 2013-06-12 00:36:25

相關問題