標籤:blog http ar 使用 sp div on art 問題
簡單的實現Google的代理:
架構就是下面這麼簡單。
=================
my server outside GFW | <----------------------> your browser visit my server at port 8080
=================
代碼如下:
#coding=utf-8from twisted.web import resource, serverfrom twisted.internet import reactor,endpointsfrom twisted.python import logimport urllib2import urllibimport syslog.startLogging(sys.stdout)class router(resource.Resource): def getChild(self, path, request): url = r‘https://www.google.com‘ if path=="": return Index(url) else: return Index(url+ request.uri)class Index(resource.Resource): def __init__(self, url): self.url = url def render_GET(self, request): req = urllib2.Request(self.url) res = urllib2.urlopen(req) return res.read()rsc = router()f = server.Site(rsc)endpoints.serverFromString(reactor, ‘tcp:8001‘).listen(f)reactor.run()
使用上面代碼有一個問題,Google對於被爬是不爽的。因此需要偽裝下,加上一個headers參數給request請求。
headers = {‘User-Agent‘:‘Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6‘} req = urllib2.Request(self.url, headers=headers)
這樣就解決了403問題。那麼接下來只要變成一個系統背景工作就可以了。
使用twisted.web實現Proxy 伺服器