Skip to main content

Python >= 3.6

requests_tor

Release history: https://pypi.org/project/requests-tor/#history


Multithreading requests via TOR with automatic TOR new identity.

Wrapper of the requests and stem libraries. Returns requests.Response object.

Masking as Tor Browser by using its default headers:

    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
    "Accept-Encoding": "gzip, deflate, br",
    "Accept-Language": "en-US,en;q=0.5",
    "Upgrade-Insecure-Requests": "1",
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; rv:102.0) Gecko/20100101 Firefox/102.0",

Install

pip install -U requests_tor

Dependencies

Download and start Tor Browser or install Tor

Notes:

  • In Tor torrc file control port is disabled by default. Needs to uncomment line ControlPort 9051
  • If you face an error Authentication failed: unable to read '/run/tor/control.authcookie' ([Errno 13] Permission denied: '/run/tor/control.authcookie') - needs to add your current user to the tor group. ps ax o comm,group | grep tor - command to find tor group (group name will be in the second column, for example debian-tor). sudo usermod -a -G debian-tor $USER - add your current user to tor group
  • Restart Tor (/etc/init.d/tor restart) and re-login

Simple usage

from requests_tor import RequestsTor

# If you use the Tor browser
rt = RequestsTor()
OR
# If you use the Tor
rt = RequestsTor(tor_ports=(9050,), tor_cport=9051)

url = 'https://httpbin.org/anything'
r = rt.get(url)
print(r.text)

urls = ['https://foxnews.com', 'https://nbcnews.com', 'https://wsj.com/news/world',
        'https://abcnews.go.com', 'https://cbsnews.com',  'https://nytimes.com',
        'https://usatoday.com','https://reuters.com/world', 'http://bbc.com/news',
        'https://theguardian.com/world', 'https://cnn.com', 'https://apnews.com']
r = rt.get_urls(urls)
print(r[-1].text)

Advanced usage

Edit torrc file:

  1. add socks ports,
SocksPort 9000 IsolateDestAddr
SocksPort 9001 IsolateDestAddr
SocksPort 9002 IsolateDestAddr
SocksPort 9003 IsolateDestAddr
SocksPort 9004 IsolateDestAddr
  1. add password for control port [not necessary]:

generate and add in torrc file HashedControlPassword.

HashedControlPassword hashed_password

from requests_tor import RequestsTor

rt = RequestsTor(tor_ports=(9000, 9001, 9002, 9003, 9004), tor_cport=9151, password=None,
                 autochange_id=5, threads=8)
"""
    tor_ports = specify Tor socks ports tuple (default is (9150,), as the default in Tor Browser),
    if more than one port is set, the requests will be sent sequentially through the each port;
    tor_cport = specify Tor control port (default is 9151 for Tor Browser, for Tor use 9051);
    password = specify Tor control port password (default is None);
    autochange_id = number of requests via a one Tor socks port (default=5) to change TOR identity,
    specify autochange_id = 0 to turn off autochange Tor identity;
    threads = specify threads to download urls list (default=8);
    """
    
# check your ip
rt.check_ip()

# new Tor identity. Сalling this function includes time.sleep(3)
rt.new_id()

# test automatic TOR new identity
rt.test()

# Requests. TOR new identity is executed after (autochange_id * len(tor_ports)) requests.
# GET request. 
rt.get(url, params=None, **kwargs)

# POST request. 
rt.post(url, data=None, json=None, **kwargs)

# PUT request. 
rt.put(url, data=None, **kwargs)

# PATCH request.
rt.patch(url, data=None, **kwargs)

# DELETE request.
rt.delete(url, **kwargs)

# HEAD request.
rt.head(url, **kwargs)

"""
    url – URL for the new Request object.
    params – dictionary, list of tuples or bytes to send in the query string.
    **kwargs – optional arguments that request takes:
        data – (optional) Dictionary, list of tuples, bytes, or file-like object 
                to send in the body of the request.
        json – (optional) A JSON serializable Python object 
                to send in the body of the Request.
        headers – (optional) Dictionary of HTTP Headers to send with the Request.
        cookies – (optional) Dict or CookieJar object to send with the Request.
        files – (optional) Dictionary of 'name': file-like-objects (or {'name': file-tuple}) 
            for multipart encoding upload. file-tuple can be a 2-tuple ('filename', fileobj), 
            3-tuple ('filename', fileobj, 'content_type') or a 4-tuple ('filename', fileobj, '
            content_type', custom_headers), where 'content-type' is a string defining the 
            content type of the given file and custom_headers a dict-like object containing 
            additional headers to add for the file.
        auth – (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth.
        timeout – (optional) How many seconds to wait for the server to send data before 
                giving up, as a float, or a (connect timeout, read timeout) tuple.
        allow_redirects (bool) – (optional) Boolean. 
            Enable/disable GET/OPTIONS/POST/PUT/PATCH/DELETE/HEAD redirection. Defaults to True.
        proxies – (optional) Dictionary mapping protocol to the URL of the proxy.
        verify – (optional) Either a boolean, in which case it controls whether we verify 
            the server’s TLS certificate, or a string, in which case it must be a path to 
            a CA bundle to use. Defaults to True.
        stream – (optional) if False, the response content will be immediately downloaded.
        cert – (optional) if String, path to ssl client cert file (.pem). 
                If Tuple, (‘cert’, ‘key’) pair.
        """

Examples

1. Get url with unique params and headers in request.

from requests_tor import RequestsTor

rt = RequestsTor(tor_ports=(9000, 9001, 9002, 9003, 9004), autochange_id=5)

url = 'https://httpbin.org/anything'
params = {
    "id": 12345,
    "status": 'passed'
    }
headers = {
    "Origin": "https://www.foxnews.com",
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36"
    }
r = rt.get(url, params=params, headers=headers)
print(r.text)  

2. Get list of urls concurrently.

from requests_tor import RequestsTor

rt = RequestsTor(tor_ports=(9000, 9001, 9002, 9003, 9004), autochange_id=5)

# get urls list concurrently. TOR new identity is executed depending on the number of socksports and 
# autochange_id parameter. In case of 5 socksports and autochange_id=5, after downloading 5*5=25 urls
# TOR identity will be changed. It does matter, because calling TOR new identity includes time.sleep(3).
# get_urls(urls) can accept params, headers and other arguments from requests library.
urls = (f'https://checkip.amazonaws.com' for _ in range(10))
results = rt.get_urls(urls)
for r in results:
    print(r.text) 

3. Get list of urls concurrently with unique ip for each url

from requests_tor import RequestsTor

rt = RequestsTor(tor_ports=(9000, 9001, 9002, 9003, 9004), autochange_id=1)

urls = (f'https://habr.com/ru/post/{x}' for x in range(1, 51))
r = rt.get_urls(urls)
print(r[-1].text)

Metadata

Release files for requests-tor 1.4

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for requests-tor 1.4
File Size Uploaded
requests_tor-1.4.tar.gz 6.7 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for requests-tor 1.4
File Interpreter ABI Platform
requests_tor-1.4-py3-none-any.whl Python 3 none any Details

Total release size: 14.0 kB

Release files / requests_tor-1.4.tar.gz

Download URL requests_tor-1.4.tar.gz
Size 6.7 kB
Tags Source
SHA-256 checksum
How to use checksums
f7dcea87fc40105294ef6ea7c3ff665bed161262dac562c169d33cd2e9ee18f3
BLAKE2b-256 checksum
How to use checksums
66d1e14635310900e17c13bdf331c805034e7116a6bc91aff12fced4b21d12e2
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/4.0.2 CPython/3.11.0

Release files / requests_tor-1.4-py3-none-any.whl

Download URL requests_tor-1.4-py3-none-any.whl
Size 7.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
817274861a57e821b77df6db3ecd4253f5b9a103d7e4e7b408c035f1e5016fa5
BLAKE2b-256 checksum
How to use checksums
099a8c91c538db50caa65027774052f91f12cf8ad36d3097d45acc8f270d6574
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/4.0.2 CPython/3.11.0

Release history Release notifications | RSS feed

This release

1.4 This release

2 release files

1.3

2 release files

1.2.1

2 release files

1.2

2 release files

1.1.2

2 release files

1.1.1

2 release files

1.1

2 release files

1.0

2 release files

0.9

2 release files

0.8

2 release files

0.7

2 release files

0.6.2

2 release files

0.6.1

2 release files

0.6

2 release files

0.5

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page