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 127.0.0.1:9050 (localhost:9050)

In requests you can use it

proxy = {
    'http':  'socks5://127.0.0.1:9050',
    'https': 'socks5://127.0.0.1:9050',
}

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

And here minimal working code. I use http://icanhazip.com to get IP address as text.

import requests

proxy = {
    'http':  'socks5://127.0.0.1:9050',
    'https': 'socks5://127.0.0.1:9050',
}

url = 'https://icanhazip.com'

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: 146.59.155.27
direct IP: 217.99.86.56

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(('127.0.0.1', 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:
    controller.authenticate(password='your_password')
    controller.signal(Signal.NEWNYM)

On Linux you can also use program netcat in terminal

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

and you can test IP with

curl https://icanhazip.com
curl --proxy 'socks5://127.0.0.1:9050' https://icanhazip.com

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 »