Hai我想在python中使用私有代理。请帮我在我当前的Python脚本中添加代理的用户名,密码。我知道要添加几行才能成功运行。
data = urllib.urlencode(values)
proxy_support = urllib2.ProxyHandler({"http": httpproxy})
opener = urllib2.build_opener(proxy_support)
urllib2.install_opener(opener)
req = urllib2.Request(url)
response = urllib2.urlopen(req,data)
page = response.read()
提前致谢!
答案 0 :(得分:0)
过时,但我找到了一个可能解决此问题的网站。
http://code.activestate.com/recipes/523016-using-xmlrpc-with-authenticated-proxy-server/
相关代码: import base64 import urllib 来自urllib import unquote,splittype,splithost import xmlrpclib
class UrllibTransport(xmlrpclib.Transport):
def set_proxy(self, proxy):
self.proxyurl = proxy
def request(self, host, handler, request_body, verbose=0):
type, r_type = splittype(self.proxyurl)
phost, XXX = splithost(r_type)
puser_pass = None
if '@' in phost:
user_pass, phost = phost.split('@', 1)
if ':' in user_pass:
user, password = user_pass.split(':', 1)
puser_pass = base64.encodestring('%s:%s' % (unquote(user),
unquote(password))).strip()
urlopener = urllib.FancyURLopener({'http':'http://%s'%phost})
if not puser_pass:
urlopener.addheaders = [('User-agent', self.user_agent)]
else:
urlopener.addheaders = [('User-agent', self.user_agent),
('Proxy-authorization', 'Basic ' + puser_pass) ]
host = unquote(host)
f = urlopener.open("http://%s%s"%(host,handler), request_body)
self.verbose = verbose
return self.parse_response(f)
if __name__ == '__main__':
proxy = "http://proxy_user:proxy_passwd@my.authenticated.proxy.server:8080"
p = UrllibTransport()
p.set_proxy(proxy)
它创建一个包含身份验证的urllib2传输类。
答案 1 :(得分:0)
httpproxy
变量的价值是多少?你试过吗
httpproxy = 'http://username:password@proxyurl:proxyport'
顺便说一下,urrlib2
无缝handles http_proxy
环境变量用于代理配置,no_proxy
用于代理免除。例如,代码之后的* nix平台应该可以工作:
export http_proxy=http://username:password@proxyurl:proxyport