How to route urllib requests through the TOR network? [duplicate]

孤者浪人 提交于 2019-11-26 22:36:43

问题


How to route urllib requests through the TOR network?


回答1:


This works for me (using urllib2, haven't tried 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')



回答2:


Tor works as a proxy, right? So ask yourself "How do I use proxies in urllib?"

Now, when I look at the docs, first thing I see is

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

which seems pretty suggestive to me...




回答3:


I managed to do an urlib.request for an onion url I found a solution based on this post: Python 3.2 : urllib, SSL and TOR through socket : error with fileno function

here is the modified code:

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()))


来源:https://stackoverflow.com/questions/711351/how-to-route-urllib-requests-through-the-tor-network

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!