Which exception is raised when an element is not found in an HTML DOM using XPath in Selenium?


If an element is not found in an HTML DOM using xpath, then the NoSuchElementException is raised. This exception is thrown when the webdriver makes an attempt to locate a web element which is absent from DOM. This is normally encountered if we create an incorrect xpath for an element.

The below image shows an example of NoSuchElementException..

Example

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class ElemntsText{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",
         "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL launch
      driver.get("https://www.tutorialspoint.com/upsc_ias_exams.htm");
      //identify an element with tagname
      WebElement e = driver.findElement(By.tagName("h2"));
      String str = e.getText();
      driver.quit();
   }
}

Output

Updated on: 06-Apr-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements