4
votes

Unable to use Tor with Python Requests

import requests
proxies = {
    'http': 'socks5://localhost:9050',
    'https': 'socks5://localhost:9050'
}
url = 'http://httpbin.org/ip'
print(requests.get(url, proxies=proxies).text)

I have tried a multitude of solutions, none of which worked for me. I am trying to make simple requests with Python through Tor. Thanks in advance.

Error:

requests.exceptions.ConnectionError: SOCKSHTTPSConnectionPool(host='canihazip.com', port=443): Max retries exceeded with url: / (Caused by NewConnectionError('< urllib3.contrib.socks.SOCKSHTTPSConnection object at 0x031B77F0>: Failed to esta blish a new connection: [Errno 10061] No connection could be made because the ta rget machine actively refused it',))

1
Tor browser listens on port 9150, not 9050 (used by tor expert bundle / tor daemon). - drew010
Thank you this fixed it. - Vaxe

1 Answers

2
votes

First make sure you pip3 install requests[socks], or if using zsh, pip3 install "requests[socks]"

Then do this:

import requests
session = requests.session()
proxies = {
    'http': 'socks5h://localhost:9050',
    'https': 'socks5h://localhost:9050'
}
session.get(url, proxies=proxies)

Note The h in socks5h://

Also, you will have to have tor running on your computer (not the browser). You can install tor using homebrew by running brew install tor.

You an start a tor instance by simply running tor in terminal.