10-穿墙代理的设置
郑昀 201005 隶属于《01.数据抓取》小节
我们访问 Twitter 等被封掉的网站时,需要设置 Proxy 。
1.使用HTTP Proxy
下面是普通HTTP Proxy的设置方式:
1.1.pycurl 的设置
_proxy_connect = "http://127.0.0.1:1984"
c = pycurl.Curl()
…
c.setopt(pycurl.PROXY, _proxy_connect)
1.2.urllib2 的设置
req = urllib2.Request(link)
proxy = urllib2.ProxyHandler({'http':'http://127.0.0.1:1984'})
opener = urllib2.build_opener(proxy,urllib2.HTTPHandler)
urllib2.install_opener(opener)
req.add_header('User-Agent', URLLIB2_USER_AGENT)
urllib2.urlopen(link)
…
opener.close()
1.3.httplib 的设置
conn = httplib.HTTPConnection("127.0.0.1",1984)
conn.request("GET", "http://www.python.org/index.html")
r = conn.getresponse()
print r.status, r.reason
1.4.httplib2 的设置
import httplib2
import socks
httplib2.debuglevel=4
h = httplib2.Http(proxy_info = httplib2.ProxyInfo(socks.PROXY_TYPE_HTTP, 'proxy_host', proxy_port))
r,c = h.request(http://bitworking.org/news/)
socks 库需要安装,主页地址:http://socksipy.sourceforge.net/ ,它不需要安装,下载源代码包后直接把 socks.py 复制到 Python's lib/site-packages 目录即可。
httplib2 则用 easy_install httplib2 安装即可。
1.5.socket代理
参见《python中的socket代理》可知,更底层的socket代理如下所示:
import socks, socket
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "proxy_host", proxy_port)
socket.socket = socks.socksocket
需要 socks 库。
1.6.twisted.web.client 的设置
from twisted.internet import reactor
from twisted.web import client
class ProxyClientFactory(client.HTTPClientFactory):
def setURL(self, url):
client.HTTPClientFactory.setURL(self, url)
self.path = url
factory = ProxyClientFactory('http://url_you_want')
reactor.connectTCP('http://proxy_host', proxy_port, factory)
reactor.run()
如果代理需要Basic身份验证,如代理地址是:http://user:pwd@host:port
,那么就用到proxy-authenticate header了:
import base64
# Proxy credentials
proxyAuth = base64.encodestring('%s:%s' % (proxy_username,proxy_password))
proxy_authHeader = "Basic " + proxyAuth.strip()
factory.headers={'Proxy-Authenticate': proxy_authHeader}
reactor.connectTCP('http://proxy_host', proxy_port, factory)
只要把Proxy-Authenticate header字段设置好,前面的httplib/urllib2等如法炮制,可参考 Python2.6的 test_urllib2 示范代码中的 test_proxy_basic_auth 函数。
2.使用HTTPS Proxy
如果代理是HTTPS的,并需要证书,那么请参考 python-httpclient 的写法。
2.1.urllib2 的设置
Python 2.X可参考 Recipe 456195 的代码。或参见 Python2.6的 test_urllib2 示范代码中的 test_proxy_https 函数。
Python 3k的参见 revision 74204。
参考资源:
1、python-httpclient:
This project aims to provide an HTTP client library for Python to address some of the shortcomings of httplib and urllib2;
2、Does python twisted framework HttpClient access proxy? ;
3、How do I switch this Proxy to use Proxy-Authentication? ;
5、Recipe 456195: urrlib2 opener for SSL proxy (CONNECT method) 。