Click on button element based on its value in Selenium Python

Question:

There is HTML code like below:

<input type="button" name="" value="back" onclick="window.history.back(1)" class="back-btn">

I want to click on it based on its value (back):

elements = driver.find_elements_by_link_text('back')
for element in elements:
    element.click()

But it does not work.

Asked By: Mahdi

||

Answers:

Look like you can select based on class name

elements=driver.find_elements_by_class_name("back-btn")
for element in elements:
    element.click()

If you cant use class try selecting all input tags and filter by attribute

elements=driver.find_elements_by_tag_name("input")
for element in elements:
    if element.get_attribute("value")=="back":
        element.click()
Answered By: Bendik Knapstad

You can use css_selector

driver.find_element_by_css_selector('[value="back"]')

Or xpath

driver.find_element_by_xpath('//input[@value="back"]')
Answered By: Guy

This was easy for me

driver.find_element_by_link_text("back").click()
Answered By: Joyson Martinraj

Given the HTML:

<input type="button" name="" value="back" onclick="window.history.back(1)" class="back-btn">

Its an <input> element with the attribute value as back.


Solution

Using the value attribute to click on the element you can use either of the following locator strategies:

  • Using css_selector:

    driver.find_element(By.CSS_SELECTOR, "input[value='back']").click()
    
  • Using xpath:

    driver.find_element(By.XPATH, "//input[@value='back']").click()
    
  • Note: You have to add the following imports :

    from selenium.webdriver.common.by import By
    

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

  • Using CSS_SELECTOR:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input[value='back']"))).click()
    
  • Using XPATH:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@value='back']"))).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
    
Answered By: undetected Selenium
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.