0

So I was using TOR to act as a way of changing my proxies and ip addresses for my webdriver. Here is the code. All dependencies are installed (including Geckodriver and latest version of Firefox).

from stem import Signal
from stem.control import Controller
from selenium import webdriver
from selenium.webdriver.firefox.options import Options
from bs4 import BeautifulSoup

def switchIP():
    with Controller.from_port(port = 9051) as controller:
        controller.authenticate()
        controller.signal(Signal.NEWNYM)


def my_proxy(PROXY_HOST,PROXY_PORT):
    fp = webdriver.FirefoxProfile()
    fp.set_preference("network.proxy.type", 1)
    fp.set_preference("network.proxy.socks",PROXY_HOST)
    fp.set_preference("network.proxy.socks_port",int(PROXY_PORT))
    fp.update_preferences()
    options = Options()
    options.headless = True
    return webdriver.Firefox(options=options, firefox_profile=fp)

for x in range(10):
    proxy = my_proxy("127.0.0.1", 9050)
    proxy.get("https://whatsmyip.com/")
    html = proxy.page_source
    soup = BeautifulSoup(html, 'lxml')
    print(soup.find("span", {"id": "ipv4"}))
    print(soup.find("span", {"id": "ipv6"}))
    switchIP()

Thanks for the help, Aarav.

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
AaravM4
  • 380
  • 1
  • 4
  • 21
  • Where is the connection refused error showing up or what is the stack trace? Can you confirm that Tor's SOCKS proxy is listening on port 9050 and that the controller is listening on port 9051? – drew010 Dec 12 '19 at 23:05

1 Answers1

0

This error message...

SocketError: [Errno 61] Connection refused

...implies that the connection was refused by the server.


This error can surface due to several reasons as follows:

  1. Firewall blocking the request/respose.
  2. Improper Proxy configurations.
  3. Invalid Proxy type.
  4. Invalid Proxy host.
  5. Invalid Proxy port. etc

This usecase

However I don't see any issues with your code block as such but while using to be able to change the proxies and ip addresses you need to start the torexe application using the popen() command as follows (example for OS):

import os

torexe = os.popen(r'C:\Users\user_name\path\to\Tor Browser\Browser\TorBrowser\Tor\tor.exe')

References

You can find a relevant discussion in:

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
  • I can't run .exe files because im on MAC os . Is there another way to do the above – AaravM4 Dec 12 '19 at 12:26
  • @AaravM4 Seems [popen()](https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man3/popen.3.html) does exists for MAC OSX. Try with the absolute path of e.g. `/path/to/tor` – undetected Selenium Dec 12 '19 at 12:34