Search code examples
seleniumsecuritytor

How use or enable Tor Circuit when it is in Remote Control (Selenium)?


Actually I managed control Tor Browser with Selenium, but I'd realised that Tor circuits (change of IP's) isn't enable. So exist a way to enable it? Or use the new feature called (New Identity) form code.

My enviroment is Python 3.7, tbselenium 0.4.2 and Tor Browser 9.0.2, thanks everyone.


Solution

  • Here is an example script on how to use Tor with the chrome webdriver:

    from selenium import webdriver
    from selenium.webdriver.chrome.options import Options
    from selenium.webdriver.common.proxy import Proxy, ProxyType
    
    #tor
    from stem import Signal
    from stem.control import Controller
    
    link = #some_url
    prox='socks5://127.0.0.1:9150' #This connects Selenium to the Tor Port which then connects to a Tor network
    
    while True:
    
        with Controller.from_port(port = 9051) as controller: #this is how you get a new Identity!
            controller.authenticate()
            controller.signal(Signal.NEWNYM)
    
        chrome_options = webdriver.ChromeOptions()
        chrome_options.add_argument('--proxy-server=%s' % prox) #sets conncection to your 9150 port aka Tor Network
    
        #chrome_options.add_argument('--headless') #opens headless browser
        driver = webdriver.Chrome('*path to your driver file*', chrome_options=chrome_options)
        driver.get(link)
        #perform selenium stuff
    

    You will need to install the stem library which is basically Tor API for Python. You also will have to edit the torrc file. Here you can read how to do all that.