Prithivi
Prithivi

Reputation: 11

"Unable to locate element" exception with WebDriver

I'm getting an "Unable to locate element" exception while running the below code. My expected output is First Page of GoogleResults.

public static void main(String[] args) {
    WebDriver driver;
    driver = new FirefoxDriver();
    driver.get("http://www.google.com");
    driver.manage().timeouts().implicitlyWait(45, TimeUnit.SECONDS);

    WebElement oSearchField = driver.findElement(By.name("q"));
    oSearchField.sendKeys("Selenium");

    WebElement oButton = driver.findElement(By.name("btnG"));
    oButton.click();

    //String oNext = "//td[@class='b navend']/a[@id='pnnext']";
    WebElement oPrevious;
    oPrevious = driver.findElement(By.xpath("//td[@class='b navend']/a[@id='pnprev']"));

    if (!oPrevious.isDisplayed()){
        System.out.println("First Page of GoogleResults");
    }
}

If I run the above code I get "Unable to Locate Element Exception". I know the Previous Button Element is not in the first page of the Google Search Results page, but I want to suppress the exception and get the output of the next step if condition.

Upvotes: 1

Views: 6117

Answers (1)

some_other_guy
some_other_guy

Reputation: 3414

Logical mistake -

oPrevious = driver.findElement(By.xpath("//td[@class='b navend']/a[@id='pnprev']"));

will fail or give error if WebDriver can't locate the element.

Try using something like -

public boolean isElementPresent(By by) {
    try {
        driver.findElement(by);
        return true;
    } catch (NoSuchElementException e) {
        return false;
    }
}

You can pass the xpath to the function like

boolean x = isElementPresent(By.xpath("//td[@class='b navend']/a[@id='pnprev']"));
if (!x){
    System.out.println("First Page of GoogleResults");
}

Upvotes: 1

Related Questions