Rakesh Poddar
Rakesh Poddar

Reputation: 193

Button Is Clicked but still 'Unable to locate element' error is thrown by Python Selenium

I am trying to press the Confirm button of a website whose HTML is like this

<footer>
    <button class="button btn-default page-container__footer-button" data-testid="page-container-footer-cancel" role="button" tabindex="0">Reject</button>
    <button class="button btn-primary page-container__footer-button" data-testid="page-container-footer-next" role="button" tabindex="0">Confirm</button>
</footer>

I click the Confirm button with this code :

driver.find_element_by_xpath('//*[@id="app-content"]/div/div[3]/div/div[3]/div[3]/footer/button[2]').click()

As it should be, Confirm Button is clicked by Selenium but still error this error thrown and due to which program stops.

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="app-content"]/div/div[3]/div/div[3]/div[3]/footer/button[2]"}

I know I can use Except Statement but I don't want to use it and instead would like to fix the error.

Thanks in Advance

Upvotes: 0

Views: 1104

Answers (1)

cruisepandey
cruisepandey

Reputation: 29382

You are using absolute xpath which could be brittle in nature, if Confirm text is static text for the button, you can use text itself to represent this in HTMLDOM.

//button[text()='Confirm']

There are 4 ways to click in Selenium.

I will use this xpath

//button[text()='Confirm']

Code trial 1 :

time.sleep(5)
driver.find_element_by_xpath("//button[text()='Confirm']").click()

Code trial 2 :

WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[text()='Confirm']"))).click()

Code trial 3 :

time.sleep(5)
button = driver.find_element_by_xpath("//button[text()='Confirm']")
driver.execute_script("arguments[0].click();", button)

Code trial 4 :

time.sleep(5)
button = driver.find_element_by_xpath("//button[text()='Confirm']")
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.

Note that, This is an assumption that button is not in iframe/frame or shadow root.

Update :

to scroll till bottom :

driver.execute_script("var scrollingElement = (document.scrollingElement || document.body);scrollingElement.scrollTop = scrollingElement.scrollHeight;")

Upvotes: 1

Related Questions