1

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.

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
Mahdi
  • 967
  • 4
  • 18
  • 34
  • Does this answer your question? [Selenium webdriver python, cannot find by value?](https://stackoverflow.com/questions/28610407/selenium-webdriver-python-cannot-find-by-value) – JeffC Jan 30 '20 at 21:06

4 Answers4

2

You can use css_selector

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

Or xpath

driver.find_element_by_xpath('//input[@value="back"]')
Guy
  • 46,488
  • 10
  • 44
  • 88
1

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()
Bendik Knapstad
  • 1,409
  • 1
  • 9
  • 18
0

This was easy for me

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

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
    
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352