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.

1

4 Answers 4

2

You can use css_selector

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

Or xpath

driver.find_element_by_xpath('//input[@value="back"]')
Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

Thank you for the response but the Question is click based on value, not a class. There are some other buttons with the same class on the page.
ive added by value aswell
1

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
    

Comments

0

This was easy for me

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

2 Comments

This does not answer the question. OP wants to find the element based on the value attribute.
back is the linked text defined in value attribute in this case. Hence there is no seperate text displayed for the button, this should work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.