Mahdi
Mahdi

Reputation: 1035

Click on button element based on its value in Selenium Python

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.

Upvotes: 1

Views: 6330

Answers (4)

undetected Selenium
undetected Selenium

Reputation: 193068

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
    

Upvotes: 1

Joyson Martinraj
Joyson Martinraj

Reputation: 1

This was easy for me

driver.find_element_by_link_text("back").click()

Upvotes: 0

Guy
Guy

Reputation: 50809

You can use css_selector

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

Or xpath

driver.find_element_by_xpath('//input[@value="back"]')

Upvotes: 2

Bendik Knapstad
Bendik Knapstad

Reputation: 1458

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()

Upvotes: 1

Related Questions