Menu Close

How to make requests via tor in Python

First make sure tor is running, with below code, you will construct a proxy session for tor.

import requests

def get_tor_session():
    session = requests.session()
    session.proxies = {'http':  'socks5://127.0.0.1:9050', 'https': 'socks5://127.0.0.1:9050'}
    return session

Then you can test your session via:

session = get_tor_session()
print('Tor IP')
print(session.get("http://httpbin.org/ip").text)

you can also use the stem library, which is a Python implementation of the Tor protocol. To use stem, you will need to install it first by running pip install stem in your terminal or command prompt.

Once stem is installed, you can use it to make requests via Tor by following these steps:

  1. Import the necessary modules from the stem library:
  2. Connect to the Tor network by creating a Controller object:
  3. Send a SIGNAL NEWNYM signal to the Tor network to change your IP address
  4. Use the requests library to make a request via Tor
from stem import Signal
from stem.control import Controller
import requests

with Controller.from_port(port = 9051) as controller:
    controller.authenticate()
    controller.signal(Signal.NEWNYM)

with Controller.from_port(port = 9051) as controller:
    controller.authenticate()
    controller.signal(Signal.NEWNYM)

    # Make a request via Tor
    response = requests.get("https://orthogonal.info")
    print(response.text)

Leave a Reply

Your email address will not be published. Required fields are marked *