How to only send certain requests with Tor in python?

时光毁灭记忆、已成空白 提交于 2019-12-11 15:29:46

问题


right now i am using the following code to port my python through tor to send requests:

socks.set_default_proxy(socks.SOCKS5, "127.0.0.1", 9450)

socket.socket = socks.socksocket

I put this at the front of my code and then start sending requests, and all my requests will be sent through tor.

In my code I need to send a lot of requests, but only 1 of them needs to actually go through tor. The rest of them don't have to go through tor.

Is there any way I can configure my code so that I can choose which requests to send through tor, and which to send through without tor?

Thanks


回答1:


Instead of monkey patching sockets, you can use requests for just the Tor request.

import requests
import json

proxies = {
    'http': 'socks5h://127.0.0.1:9050',
    'https': 'socks5h://127.0.0.1:9050'
}

data = requests.get("http://example.com",proxies=proxies).text

Or if you must, save the socket.socket class prior to changing it to the SOCKS socket so you can set it back when you're done using Tor.

socks.set_default_proxy(socks.SOCKS5, "127.0.0.1", 9450)

default_socket = socket.socket
socket.socket = socks.socksocket
# do stuff with Tor
socket.socket = default_socket


来源:https://stackoverflow.com/questions/47971593/how-to-only-send-certain-requests-with-tor-in-python

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