import urllib2
proxy = urllib2.ProxyHandler({ "http" : "http:proxyIp1", "https" : "proxyIp2"})
opener = urllib2.build_opener(proxy)
urllib2.install_opener(opener)
try:
a = urllib2.urlopen("corporate internal link")#, proxies=proxy)
b = a.read()
except urllib2.HTTPError as e:
error = e.read() # this will be your error message
print error
这会出错:
401 - Unauthorized: Access is denied due to invalid credentials.
我知道我必须提供“用户名”和“密码”但是可以告诉我如何在这种情况下提供凭据? 感谢
答案 0 :(得分:0)
来源:http://docs.python.org/2/library/urllib2.html选中“使用基本HTTP身份验证”
了解add_password
方法here
proxy_handler = urllib2.ProxyHandler({'http': 'http://www.example.com:3128/'})
proxy_auth_handler = urllib2.ProxyBasicAuthHandler()
proxy_auth_handler.add_password('realm', 'host', 'username', 'password')
opener = urllib2.build_opener(proxy_handler, proxy_auth_handler)
# This time, rather than install the OpenerDirector, we use it directly:
opener.open('http://www.example.com/login.html')