How to Make Tor Requests in Python

TOR (The Onion Router) is free software that enables anonymous communication on the Internet. You can install TOR on all your devices from Linux to Windows. You can download it from its official website.

A few days ago, I was wondering how to make anonymous requests in Python. It turned out to be easier than I thought.

Firstly, you need to install Tor on your computer. You can select your platform to download Tor. Here is how to do it in Linux:

sudo apt-get install tor

After you installed it, you should enable the service.

sudo service tor start

Once it's enabled, you can use this Python function to make tor requests.

# Be sure you've installed pysocks and requests libraries
# pip install requests pysocks stem

import requests

def get_tor_session():
    session = requests.session()
    # Tor uses the 9050 port as the default socks port
    session.proxies = {'http':  'socks5://',
                       'https': 'socks5://'}
    return session

# Make a request through the Tor connection
# IP visible through Tor
session = get_tor_session()
# Above should print an IP different than your public IP

# Above should print an IP different than your public IP
# Following prints your normal public IP