Search on blog:

Python: How to use Tor Network with requests to change IP?

Tor Network can be used to run requests with changed IP.

If you have installed Tor then it should run all time as service and you could use it as proxy server with address (localhost:9050)

In requests you can use it

proxy = {
    'http':  'socks5://',
    'https': 'socks5://',

r = requests.get(url, proxies=proxy)  # using TOR network

And here minimal working code. I use to get IP address as text.

import requests

proxy = {
    'http':  'socks5://',
    'https': 'socks5://',

url = ''

r = requests.get(url, proxies=proxy)  # using TOR network
print('   Tor IP:', r.text)

r = requests.get(url)
print('direct IP:', r.text)

and this moment it shows me:

   Tor IP:
direct IP:

But Tor will use almost all time the same IP.

If you want to change its IP then you have to restart/reload Tor.

Or you would have to configure ControlPort (usually 9051) and Password in Tor settings (on Linux in file /etc/tor/torrc)

and then you can change Tor IP by sending signal with socket

import socket

s = socket.socket()
s.connect(('', 9051))
s.send('AUTHENTICATE "your_passord"\r\nSIGNAL NEWNYM\r\n'.encode())

or you can use module stem for this

from stem import Signal
from stem.control import Controller

with Controller.from_port(port=9051) as controller:

On Linux you can also use program netcat in terminal

printf 'AUTHENTICATE "password"\r\nSIGNAL NEWNYM\r\n' | nc 9051

and you can test IP with

curl --proxy 'socks5://'

As I know after sending signal sometimes Tor may need few seconds to get new IP address so you may have to wait few seconds before sending next request with new IP.

« Page: 1 / 1 »