请教大神帮忙看看,为什么无法挂上代理,一直提示:
HTTP Error 407: authenticationrequired
import urllib2
enable_proxy = True
proxy = "http" : "openproxy.com:8080"
proxy_handler = urllib2.ProxyHandler({proxy})
null_proxy_handler = urllib2.ProxyHandler({})
if enable_proxy:
opener = urllib2.build_opener(proxy_handler)
else:
opener = urllib2.build_opener(null_proxy_handler)
urllib2.install_opener(opener)
req = urllib2.Request("http://www.baidu.com/")
urllib2.urlopen(req)
我只是 来路过的
在网上搜了很久,终于找到了这个解决方法
一般代理都需要验证用户名密码,用这种写法可行。(需要Basic认证,具体原因不清楚)
def url_build_proxy_opener(proxy_info):
passmgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
passmgr.add_password(None, proxy_info['server'] , proxy_info['user'], proxy_info['password'])
auth = urllib2.ProxyBasicAuthHandler(passmgr)
opener = urllib2.build_opener(urllib2.ProxyHandler({'http':proxy_info['server']}) , auth)
return opener
proxy_info = {'user':'xxxx', 'password':'xxxx' , 'server':'openproxy.xxxx.com:8080'}
opener = url_build_proxy_opener(proxy_info)
urllib2.install_opener(opener)
而直接在ProxyHandler加入用户名密码是不行的:
proxy = 'http://%s:%s@%s:%s' % ('xxxx', 'xxxx', 'openproxy.com', 8080)
proxy_handler = urllib2.ProxyHandler({"http" : proxy})