HOW TO HANDLE NOSUCHELEMENT EXCEPTION IN JAVA SELENIUM
- Amruta Bhaskar
- Mar 3, 2020
- 0 comment(s)
This commonly seen exception class is a subclass of class. The exception occurs when WebDriver is unable to find and locate elements.
Usually, this happens when the tester writes incorrect element locator in the findElement(By, by) method.
Consider that in the below example, correct XPath expression for the Login button was //div[.='Login '] but the tester incorrectly mentioned it as //div[.='Login'] if you observe, the tester has forgotten to give space after login word as in this case, space is also a character. Here, WebDriver cannot locate the element and driver.findElement(By.xpath("//div[.='Login']")).click(); will be thrown by
To Handle this exception, we have to copy the expression from the source code along
with the spaces and verify using Try XPath then we can avoid this exception.
Steps to generate and solve this above exception
1. Open the chrome browser
WebDriver driver=new ChromeDriver();
2. Enter the URL of the https://demo.actitime.com/
3. Write the code to Click on login button
4. It throws NoSuchElementException as Xpath expression that you have copied is wrong.
When we copy the XPath expression we need to validate it. Hence, press Control+F. A text field will appear. Write the expression and check if it matches with an element in the webpage.
If it is matching, then copy the expression and paste in selenium code so we can avoid NoSuchElemetException.
Locators that are to be used have to be in prioritized order along with multiple XPath expressions.
To know more about NoSuchElementException, click on the link below to see its practical application.
Author: Bharani G R