1

I have the following Python code using Selenium to automate a button press:

from selenium import webdriver
import time

def main():
    page_url = 'x.htm?'
    driver = webdriver.Safari()
    driver.get(page_url)
    time.sleep(2)
    elem = driver.find_element_by_xpath('yy')
    elem.click()
    driver.quit()

if __name__ == '__main__':
    main()

I've removed the URL and button but they are valid. When I copy the code into an interactive Python console it runs and the click works; the browser is redirected. But when I run the code as as script, the click doesn't happen (the browser appears and the page renders but click is not registered).

Would love some help understanding why this is happening.

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
Clinton Boys
  • 141
  • 1
  • 5

1 Answers1

0

As you mentioned ...copy the code into an interactive Python console it runs and the click works... that implies the element doesn't turns clickable even with 2 seconds of sleep.


Solution

Ideally, to click on the element you need to induce WebDriverWait for the element_to_be_clickable() and you can use the following based Locator Strategy:

WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "yy"))).click()

Note: You have to add the following imports :

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352