13

如何通过 TOR 网络路由 urllib 请求?

4

3 回答 3

12

这对我有用(使用 urllib2,没有尝试过 urllib):

def req(url):
    proxy_support = urllib2.ProxyHandler({"http" : "127.0.0.1:8118"})
    opener = urllib2.build_opener(proxy_support) 
    opener.addheaders = [('User-agent', 'Mozilla/5.0')]
    return opener.open(url).read()

print req('http://google.com')
于 2010-07-24T01:04:08.437 回答
6

Tor 作为代理工作,对吧?所以问问自己“我如何在 urllib 中使用代理?”

现在,当查看文档时,我首先看到的是

urllib.urlopen(url[, data[, proxies]])

这对我来说似乎很有启发性......

于 2009-04-02T20:15:02.877 回答
1

我设法为洋葱 url 做了一个 urlib.request 我找到了一个基于这篇文章的解决方案:Python 3.2 : urllib, SSL and TOR through socket : error with fileno function

这是修改后的代码:

import socks
import socket

# This function has no DNS resolve
# it need to use the real ip adress to connect instead of www.google.com
def create_connection_fixed_dns_leak(address, timeout=None, source_address=None):
    sock = socks.socksocket()
    sock.connect(address)
    return sock

# MUST BE SET BEFORE IMPORTING URLLIB
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050)
# patch the socket module
socket.socket = socks.socksocket
socket.create_connection = create_connection_fixed_dns_leak

from urllib import request

if __name__ == "__main__":
    for proxy in request.getproxies():
        print(str(proxy))
    url = 'http://url_of_hidden_service.onion:port'
    req = request.Request(url)
    res = request.urlopen(req)
    print(str(res.read()))
于 2014-12-12T05:02:53.837 回答