Python网络编程基础笔记-urllib2身份验证
# -*- coding: cp936 -*-
"""
使用身份验证
1.创建继承于urllib2.HTTPPasswordMgr
2.重载find_user_password
3.创建OpenerMgr实例
结果是:如果请求的url需要身份验证,此程序会提示输入用户名和密码,如果无法通过身份验证,程序异常.
"""
import sys,urllib2,getpass
# 创建HTTPPasswordMgr类
class TerminalPassword(urllib2.HTTPPasswordMgr):
# 重载find_user_password方法
def find_user_password(self,realm,authuri):
retval = urllib2.HTTPPasswordMgr.find_user_password(self,realm,authuri)
if retval[0] == None and retval[1] == None:
sys.stdout.write("Login required for %s at %s\n" % (realm,authuri))
sys.stdout.write("Username:")
username = sys.stdin.readline().rstrip()
password = getpass.getpass().rstrip()
return (username,password)
else:
return retval
req = urllib2.Request("http://www.unicode.org/mail-arch/unicode-ml")
# 创建opener
opener = urllib2.build_opener(urllib2.HTTPBasicAuthHandler(TerminalPassword()))
fd = opener.open(req)
print ("Retrieved",fd.geturl())
info = fd.info()
for key,value in info.items():
print ("%s = %s" % (key,value))