2016-04-11 6 views
0

urllib2ライブラリとadd_header関数を使用して、私はPython 2.7でデータを認証して取得できます。しかし、より多くのpython 3でurllib2ライブラリから、どのように私はurllibライブラリで基本認証ヘッダーを追加するのですか?pythonで認証ヘッダーを追加する3

+0

自分を支持し、使用要求はhttpかの操作を行います// docs.python-requests.org/ja/master/api/ –

答えて

1

の方法をurllib.requestの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') 

関連する問題