Pythonの標準モジュールurllib2を使ってHTTP クライアントを作ってみよう(5) - Basic 認証編 -の例題ページに接続する実験。ほとんどここの写しだが、一部変更しないと認証がうまくいかなかった。


import urllib2
toplevelurl='x68000.q-e-d.net'
theurl='x68000.q-e-d.net/~68user/net/sample/http-auth/secret.html'
protocol='http://'
username='hoge'
password='fuga'
passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, toplevelurl, username, password)
authhandler = urllib2.HTTPBasicAuthHandler(passman)
opener = urllib2.build_opener(authhandler)
urllib2.install_opener(opener)
pagehandle = urllib2.urlopen(protocol + theurl)