Python 使用urllib2的基本身份验证

Python 使用urllib2的基本身份验证,python,urllib2,Python,Urllib2,我一直在努力访问某个网页,但很难做到这一点。下面是代码。你能告诉我我错过了什么吗?请注意,我可以访问公司局域网内的所有链接。这只是外部链接的问题。我得到了一个带有WWW认证密钥的401 #!/usr/bin/python -w import urllib2 myURL = 'http://www.yahoo.com' username = 'uname' passwd = 'password' req = urllib2.Request(myURL) print req try:

我一直在努力访问某个网页,但很难做到这一点。下面是代码。你能告诉我我错过了什么吗?请注意,我可以访问公司局域网内的所有链接。这只是外部链接的问题。我得到了一个带有WWW认证密钥的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"   

我可以访问公司局域网内的所有链接。您局域网中的任何链接都在使用身份验证?我不必在局域网中使用身份验证。