简体   繁体   English

urllib2请求代理的格式是什么?

[英]What's the format for urllib2 request proxies?

According to the documentation, this is the format: 根据文档,此格式为:

Request.set_proxy(host, type)

So what I have is this for example: 所以我有这个例子:

Request.set_proxy("localhost:8888","http")

What is the format if the proxy requires a username and password? 如果代理需要用户名和密码,格式是什么?

Two ways to do this if you must use a urllib2.Request object: 如果必须使用urllib2.Request对象,可以通过两种方法进行:

Set environment variables http_proxy and/or https_proxy either outside of the Python interpreter, or internally using os.environ['http_proxy'] before you import urllib2 . 在导入urllib2之前,可以在Python解释器之外或内部使用os.environ['http_proxy']设置环境变量http_proxy和/或https_proxy

import os
os.environ['http_proxy'] = 'http://user:password@localhost:8888'
import urllib2
req = urllib2.Request('http://www.blah.com')
f = urllib2.urlopen(req)

Or manually set HTTP request header: 或手动设置HTTP请求标头:

import urllib2
from base64 import urlsafe_b64encode
PROXY_USERNAME = 'user'
PROXY_PASSWORD = 'password'
req = urllib2.Request('http://www.blah.com')
req.set_proxy('localhost:8888', 'http')
proxy_auth = urlsafe_b64encode('%s:%s' % (PROXY_USERNAME, PROXY_PASSWORD))
req.add_header('Proxy-Authorization', 'Basic %s' % proxy_auth)
f = urllib2.urlopen(req)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM