Home > Blockchain >  Unable to locate element when browser in background using Selenium
Unable to locate element when browser in background using Selenium

Time:12-21

I'm trying to automate this program to be handled in background while I can do my work, but I found out it gives "Unable to locate element" error when I don't have the browser active in front of other processes (like watching it). It follows people on Twitter, but like I want the program do its work. Everything is smooth when the browser is active, but as I switch to other works on my laptop, it doesn't locate the element even though it's visible.

I'm new and still learning, so I don't know if there are limitations to Selenium.

def to_follow_delay():
    def to_follow_delay_2():
        try:
            driver.get(next(urls))
            def follow_user():
                sleep(5)
                followuser = driver.find_element_by_xpath('//*[@id="react-root"]/div/div/div[2]/main/div/div/div/div/div/div[2]/div/div/div[1]/div/div[1]/div[2]/div[3]/div/div')
                sleep(5)
                followuser.click()
                #followuser = WebDriverWait(driver, 50).until(EC.presence_of_element_located((By.XPATH, '//*[@id="react-root"]/div/div/div[2]/main/div/div/div/div/div/div/div/div/div[1]/div[2]/div[1]/div[2]/div[2]/div/div')))
                print("Follow successful")
                print("--- %s seconds ---" % (time.time() - starting4))

                followedper_runcounter.set(followedper_runcounter.get()   1)
                followedcounter.set(followedcounter.get()   1)
                return operation_follow()

            timer4 = threading.Timer(tofollowdelayvalue_txt.get(), follow_user)
            timer4.start()
            starting4 = time.time()
        except StopIteration:
            print('No more urls.')
            return

       
    timer5 = threading.Timer(5, to_follow_delay_2)
    timer5.start()

CodePudding user response:

This issue usually gets resolved when you use headless mode. For Firefox the settings that you would have to include would be

options = webdriver.FirefoxOptions()
options.add_argument('-headless')
driver = webdriver.Firefox(firefox_profile = profile, executable_path = 'C:\\some path\\geckodriver.exe', options=options)
  • Related