SkillRary

Please login to post comment

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 NotFoundException 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 org.openqa.selenium. NoSuchElementException will be thrown by driver.findElement(By.xpath("//div[.='Login']")).click();

 

 

 

 

 

 

Exception Handling:

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/

driver.get("https://demo.actitime.com/login.do");

3.   Write the code to Click on login button

driver.findElement(By.xpath("//div[.='Login']")).click();

 

 

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.

https://www.youtube.com/watch?v=NSZcrV9N1HU&t=2s

 

 

Author: Bharani G R 

 

 

 

 

Please login to post comment

( 0 ) comment(s)