我正在尝试使用请求访问以下域nzxj65x32vh2fkhk.onion
我已经运行了,我正确配置了会话的对象代理。
import requests
session = requests.session()
session.proxies = {'http': 'socks5://localhost:9050',
'https': 'socks5://localhost:9050'}
print(session.get('http://httpbin.org/ip').text) # prints {"origin": "67.205.146.164" }
print(requests.get('http://httpbin.org/ip').text) # prints {"origin": "5.102.254.76" }
但是,当我尝试使用.onion域访问URL时,出现以下错误:
session.get('http://nzxj65x32vh2fkhk.onion/all')
ConnectionError: SOCKSHTTPConnectionPool(host='nzxj65x32vh2fkhk.onion', port=80): Max retries exceeded with url: /all (Caused by NewConnectionError('<requests.packages.urllib3.contrib.socks.SOCKSConnection object at 0x7f5e8c2dbbd0>: Failed to establish a new connection: [Errno -2] Name or service not known',))
我还尝试按照其中一个答案中的建议将localhost
替换为127.0.0.1
。不幸的是,结果是一样的。
使用urllib2执行相同的请求就可以了。
import socks, socket, urllib2
def create_connection(address, timeout=None, source_address=None):
sock = socks.socksocket()
sock.connect(address)
return sock
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, '127.0.0.1', 9050)
socket.socket = socks.socksocket
socket.create_connection = create_connection
print(urllib2.urlopen('http://nzxj65x32vh2fkhk.onion/all').read()) # Prints the URL's contents
cURL还会正确检索页面内容。
我正在使用Python 2.7.13,请求2.13.0&amp; PySocks 1.6.7。 Tor使用以下命令通过docker容器运行:
sudo docker run -it -p 8118:8118 -p 9050:9050 -d dperson/torproxy
我在这里做错了什么?我需要做什么才能使请求识别.onion URL?
答案 0 :(得分:5)
解决方案是使用socks5h
协议,以便在本地DNS解析过程失败时启用远程DNS解析。 See https://github.com/kennethreitz/requests/blob/e3f89bf23c53b98593e4248054661472aacac820/requests/packages/urllib3/contrib/socks.py#L158
以下代码按预期工作:
import requests
session = requests.session()
session.proxies = {'http': 'socks5h://localhost:9050',
'https': 'socks5h://localhost:9050'}
print(session.get('http://httpbin.org/ip').text) # prints {"origin": "67.205.146.164" }
print(requests.get('http://httpbin.org/ip').text) # prints {"origin": "5.102.254.76" }
print(session.get('http://nzxj65x32vh2fkhk.onion/all').text) # Prints the contents of the page