Turn your manual testers into automation experts! Request a DemoStart testRigor Free

NotFoundException in Selenium Explained

Exceptions in Selenium are errors that happen during test execution. These exceptions are raised when an unexpected issue occurs during test execution. They help to identify and handle problems in our script. One of the common exceptions that we see in Selenium is NotFoundException. So, let’s discuss this exception, its root cause, and how we can resolve it.

NotFoundException in detail

In Selenium, NotFoundException is raised when it cannot locate the element on the web page based on the specified selector or criteria. This exception typically occurs when we use the Selenium methods like “findElement” or “findElements” to locate and interact with elements such as buttons, input fields, links, etc. There are many reasons for which this exception can be thrown. Let’s go through each.

  • Element Not Present: If the element we are trying to interact with is not present on the current web page, then this exception will be thrown. For example, we are attempting to find a non-existent element by its ID:
    driver.findElement(By.id("non_existent_element_id"));
  • Element Not Yet Loaded: If the element exists on the web page but is not yet visible or interactable due to loading delay or dynamic page loading, then Selenium can throw this exception while trying to find it.
  • Incorrect Selector: If we use the wrong Selector criteria, like the wrong element ID, class name, or XPath, for locating an element. Then, this exception will be thrown.
    driver.findElement(By.name("wrong_element_name"));
  • iFrame Context: When we are trying to locate an element that is inside an iframe, but we haven’t switched to the iframe, then this error will be thrown.
  • Page Not Fully Loaded: When Selenium tries to find elements before the page is fully loaded, then this exception will be thrown.
  • Dynamic Content: The dynamic contents on a web page change after the initial page load so that these elements can become unavailable or change location. So, finding these elements can throw this exception.
  • Timing Issues: Sometimes, WebDriver may try to find an element before it becomes available, leading to NotFoundException. This is mainly because of the timing issue.

Resolving NotFoundException

You can try the below tricks to avoid NotFoundException in your Selenium scripts:

Use Explicit Waits

Employ explicit waits to give the page time to load or make the element visible and interactable. For example, wait for a button to be clickable before clicking it:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
wait = WebDriverWait(driver, 10)
element = wait.until(EC.element_to_be_clickable((By.id("element_id"))))
element.click()

Modify the Locator Strategy

Double-check and adjust your selector strategy to locate the element. Consider using a more robust strategy like XPath if the element’s attributes are complex or changing:
driver.findElement(By.xpath("//input[@name='username']"))

Try-Catch Blocks

Use try-catch blocks to handle exceptions gracefully. By catching NotFoundException, you can log the error and perform alternative actions or continue the script execution:
from selenium.common.exceptions import NoSuchElementException

try:
  element = driver.findElement(By.id("element_id"))
  element.click()

except NoSuchElementException:
  print("Element not found. Taking alternative action or logging the error.")

Verify Element Presence

Before interacting with an element, you can verify its presence on the page to avoid exceptions. This is useful for elements that may or may not be present:
if driver.findElements(By.id("element_id")):
  element = driver.findElement(By.id("element_id"))
  element.click()
else:
  print("Element not found. Taking alternative action.")

Use Correct Selectors

Ensure that you use accurate and unique selectors to locate elements. Double-check the element’s attributes, such as ID, name, class, or XPath, to ensure they match the target element.
driver.findElement(By.id("correct_element_id")).click()

Handle Dynamic Content

If the page content is dynamic, use more robust selectors or XPath expressions that account for potential changes in element attributes.
driver.findElement(By.xpath("//button[contains(text(),'Click Me')]")).click()

Eliminating NotFoundException using AI

As we know, Selenium uses ID, Class names, CSS Selectors, or XPath for element locators. These all are the properties of elements in the HTML. The developers don’t need to provide class names; when we consider angular or react applications, the class names will be dynamic. So, their use is not trustworthy in the scripts and may cause instability.

Similarly, in the case of XPath, we basically use relative XPath, which is more stable than absolute XPath. But still, if there is any change in the property of elements to which the intended element refers, then XPath fails. So, XPath also is very fragile.

A failure in element locators also causes the test step to fail. The test case fails, creating a false positive bug. The automation team needs time and effort to fix the XPath and re-run the scenario. This, in turn, affects the overall execution time, delaying the sign-off of the product. This is one of the reasons for the downfall of Selenium.

Intelligent test automation tools such as testRigor have an advantage here. testRigor doesn’t use flaky XPaths. Instead, users can identify the elements with what they see on the UI or with the relative position of adjacent elements. It works just as you and I, or any human, would. testRigor, with its generative AI and NLP algorithms, will be able to identify the element. For example:
click "cart"
click on the 3rd "hello" 5 times
click on the "Cancel" to the right of "Submit"

testRigor locators are more stable and easier to write than the Selenium ones. You can read more about them here.

To know more about the features of testRigor, you can refer here.

EndNotes

Automation reports are usually monitored by different members of an organization, like the QA team, development team, managers, and, often, other stakeholders. So, the automation reports must contain the correct numbers.

Test cases failing due to changes in element locators create false positive bugs that raise the failure count. So, it’s always better to use tools like testRigor, which removes the instability in automation and creates robust and reliable automation reports.

Also, this saves the QA team a lot of time fixing the locators and unnecessary maintenance. As we know, Time is Money, and testRigor saves it for you quickly.

You can sign up for a free trial to discover its powerful features.

You're 15 Minutes Away From Automated Test Maintenance and Fewer Bugs in Production
Simply fill out your information and create your first test suite in seconds, with AI to help you do it easily and quickly.
Achieve More Than 90% Test Automation
Step by Step Walkthroughs and Help
14 Day Free Trial, Cancel Anytime
“We spent so much time on maintenance when using Selenium, and we spend nearly zero time with maintenance using testRigor.”
Keith Powe VP Of Engineering - IDT
Related Articles

SAP Concur Testing

Concur Technologies, now SAP Concur, is an American software-as-a-service (SaaS) company providing travel and expense management ...

Authorize.net Testing

You need a payment gateway in several scenarios, especially when you are running a business that requires secure, efficient, and ...

KYC Portal CLM Testing

KYC Portal CLM is an award-winning Client Lifecycle Management (CLM) platform designed to streamline and automate the Know Your ...
On our website, we utilize cookies to ensure that your browsing experience is tailored to your preferences and needs. By clicking "Accept," you agree to the use of all cookies. Learn more.
Cookie settings
Privacy Overview
This site utilizes cookies to enhance your browsing experience. Among these, essential cookies are stored on your browser as they are necessary for ...
Read more
Strictly Necessary CookiesAlways Enabled
Essential cookies are crucial for the proper functioning and security of the website.
Non-NecessaryEnabled
Cookies that are not essential for the website's functionality but are employed to gather additional data. You can choose to opt out by using this toggle switch. These cookies gather data for analytics and performance tracking purposes.