如何在python中只使用Tor发送某些请求? [英] How to only send certain requests with Tor in python?

查看:36
本文介绍了如何在python中只使用Tor发送某些请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在我正在使用以下代码通过 tor 移植我的 python 以发送请求:

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

我把这个放在我的代码前面然后开始发送请求,我所有的请求都会通过tor发送.

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

在我的代码中,我需要发送很多请求,但其中只有 1 个需要真正通过 tor.其余的不需要通过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.

有什么方法可以配置我的代码,以便我可以选择通过 Tor 发送哪些请求,以及不通过 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?

谢谢

推荐答案

你可以使用 requests 代替猴子补丁套接字 仅用于 Tor 请求.

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

或者,如果必须,请在将 socket.socket 类更改为 SOCKS 套接字之前保存它,以便在使用完 Tor 后将其重新设置.

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

这篇关于如何在python中只使用Tor发送某些请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆