2016-04-11 53 views
0

使用urllib2庫和add_header函數,我能夠在python 2.7中驗證和檢索數據。但是,由於urllib2庫在python 3中更多,我該如何使用urllib庫添加Basic Authentication標頭?在python 3中添加驗證頭文件

+0

請你幫個忙,並使用HTTP請求:// docs.python-requests.org/en/master/api/ –

回答

1

請檢查add_header方法urllib.request的請求類。

import urllib.request 
req = urllib.request.Request('http://www.example.com/') 
req.add_header('Referer', 'http://www.python.org/') 
r = urllib.request.urlopen(req) 

順便說一句,我建議你檢查的另一種方法,使用HTTPBasicAuthHandler

import urllib.request 
# Create an OpenerDirector with support for Basic HTTP Authentication... 
auth_handler = urllib.request.HTTPBasicAuthHandler() 
auth_handler.add_password(realm='PDQ Application', 
          uri='https://mahler:8092/site-updates.py', 
          user='klem', 
          passwd='kadidd!ehopper') 
opener = urllib.request.build_opener(auth_handler) 
# ...and install it globally so it can be used with urlopen. 
urllib.request.install_opener(opener) 
urllib.request.urlopen('http://www.example.com/login.html') 

(在同一頁面獲取)