使用urllib2进行基本身份验证

时间:2014-12-01 21:19:03

标签: python urllib2

我一直在努力访问某个网页,但却遇到了麻烦。下面是代码。你能告诉我我错过了什么吗?请注意,我可以访问公司LAN内的所有链接。这只是外部链接的问题。我使用WWW-Authenticate密钥获得401。

#!/usr/bin/python -w

import urllib2

myURL = 'http://www.yahoo.com'
username = 'uname'
passwd = 'password'

req = urllib2.Request(myURL)
print req

try:
    response = urllib2.urlopen(req)
    print response.read()
except urllib2.HTTPError, e:
    print e.headers
    print e.headers.has_key('WWW-Authenticate')
    print e.code
else:
    print "This page is not protected"
    sys.exit(1)

passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
passman.add_password('CTTEST', myURL, username, passwd)
authhandler = urllib2.HTTPBasicAuthHandler(passman)
opener = urllib2.build_opener(authhandler)
urllib2.install_opener(opener)

try:
    response = urllib2.urlopen(req)
except IOError, e:
    print "Incorrect Credentials"   

0 个答案:

没有答案