tonster55
tonster55

Reputation: 41

How to click on button using Selenium

I'm trying to click a button on a website with Selenium in python, and the button clicking works fine, I can see the button being clicked but the code stops running at that point and when I check the website in my normal browser I can tell that the button hasn't been clicked. More specifically, I'm trying to click a start button for an aternos.org server, and it clicks fine, but the actual starting of the server doesn't go through for some reason.

My code for the start button clicking:

start = driver.find_element(By.ID, 'start')
status = driver.find_element(By.CLASS_NAME, 'statuslabel-label').text
print(status)
if status == 'Offline':
    start.click()
    print('Starting server!')

Upvotes: 4

Views: 5063

Answers (1)

undetected Selenium
undetected Selenium

Reputation: 193058

Ideally, to locate and click any clickable element you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following locator strategies:

  • Using ID:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.ID, "start"))).click()
    
  • Using CSS_SELECTOR:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#start"))).click()
    
  • Using XPATH:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//*[@id='start']"))).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
    

Upvotes: 5

Related Questions