【发布时间】:2015-12-17 09:07:56
【问题描述】:
我正在尝试编写一个函数,该函数将获取一个 URL 并返回该 URL 的内容。还有一个附加参数 (useTor),当设置为 True 时,将使用 SocksiPy 通过 SOCKS 5 代理服务器(在本例中为 Tor)路由请求。
我可以为所有连接全局设置代理,但我无法解决两件事:
如何将此设置移动到一个函数中,以便可以在
useTor变量上决定它?我无法在函数中访问socks,也不知道该怎么做。我假设如果我不设置代理,那么下次发出请求时它会直接发送。 SocksiPy 文档似乎没有提供任何关于如何重置代理的指示。
谁能给点建议?我的(初学者)代码如下:
import gzip
import socks
import socket
def create_connection(address, timeout=None, source_address=None):
sock = socks.socksocket()
sock.connect(address)
return sock
# next line works just fine if I want to set the proxy globally
# socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050)
socket.socket = socks.socksocket
socket.create_connection = create_connection
import urllib2
import sys
def getURL(url, useTor=False):
if useTor:
print "Using tor..."
# Throws- AttributeError: 'module' object has no attribute 'setproxy'
socks.setproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050)
else:
print "Not using tor..."
# Not sure how to cancel the proxy, assuming it persists
opener = urllib2.build_opener()
usock = opener.open(url)
url = usock.geturl()
encoding = usock.info().get("Content-Encoding")
if encoding in ('gzip', 'x-gzip', 'deflate'):
content = usock.read()
if encoding == 'deflate':
data = StringIO.StringIO(zlib.decompress(content))
else:
data = gzip.GzipFile('', 'rb', 9, StringIO.StringIO(content))
result = data.read()
else:
result = usock.read()
usock.close()
return result
# Connect to the same site both with and without using Tor
print getURL('https://check.torproject.org', False)
print getURL('https://check.torproject.org', True)
【问题讨论】: