Unable to locate an element using xpath error in selenium-java


We may encounter the error - unable to locate element while working with Selenium webdriver. This leads to NoSuchElementException. This type of exception is thrown when there is no element on the page which matches with the locator value.

If error is encountered, we can fix it by the following ways −

  • Check if there is any syntax error in our xpath expression.

  • Add additional expected wait conditions for the element.

  • Use an alternative xpath expression.

Example

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class XpathError{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",
         "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      //launch URL
      driver.get("https://www.tutorialspoint.com/index.htm");
      WebElement m = driver.findElement(By.xpath("//*[text()='Library']"));
      m.click();
      //explicit wait condition - visibilityOfElementLocated
      w.until(ExpectedConditions.visibilityOfElementLocated (By.linkText("Subscribe to Premium")));
      System.out.println("Page title: " + driver.getTitle());
      driver.quit();
   }
}

Output

Updated on: 07-Apr-2021

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements