Home > Enterprise >  How to find a button in selenium?(Python)
How to find a button in selenium?(Python)

Time:10-04

I want to find this button in selenium :

<input class="button button-primary" type="submit" value="Send me the code" data-type="save">

I tried this:

driver.find_element_by_xpath("//input[@value='Send me the code']").click()

But this didn't work.

CodePudding user response:

There are many possible reasons why a simple code line like driver.find_element_by_xpath("//input[@value='Send me the code']").click() may not work properly.
The most likely reason could be missing a wait / delay. You should wait until the element is fully loaded before trying accessing it. Instead using driver.find_element_by_xpath("//input[@value='Send me the code']").click() Please try something like this:

wait.until(EC.visibility_of_element_located((By.XPATH, "//input[@value='Send me the code']"))).click()

To use this you will need the following imports:

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

And to initialize wait object

wait = WebDriverWait(driver, 20)

Also it is possible the locator is not unique.
Also the element can be located inside iframe etc.

CodePudding user response:

There are basically 4 ways to click in Selenium.

I will use this xpath

//input[@value='Send me the code']

Code trial 1 :

time.sleep(5)
driver.find_element_by_xpath("//input[@value='Send me the code']").click()

Code trial 2 :

WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@value='Send me the code']"))).click()

Code trial 3 :

time.sleep(5)
button = driver.find_element_by_xpath("//input[@value='Send me the code']")
driver.execute_script("arguments[0].click();", button)

Code trial 4 :

time.sleep(5)
button = driver.find_element_by_xpath("//input[@value='Send me the code']")
ActionChains(driver).move_to_element(button).click().perform()

Imports :

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains

PS : Please check in the dev tools (Google chrome) if we have unique entry in HTML DOM or not.

Steps to check:

Press F12 in Chrome -> go to element section -> do a CTRL F -> then paste the xpath and see, if your desired element is getting highlighted with 1/1 matching node.

  • Related