0
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.

我知道我必须提供“用户名”和“密码”,但任何人都可以告诉我在这种情况下如何提供凭据?谢谢

4

1 回答 1

0

来源:http ://docs.python.org/2/library/urllib2.html检查“使用基本 HTTP 身份验证”

在此处阅读有关add_password方法

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')
于 2013-07-02T13:06:59.590 回答