Dana
Dana

Reputation: 35

if condition getting error in selenium webdriver

    //extract the link texts of each link element

    for (WebElement Page3 : linkElements3) 
    {
        linkTitles3[k] = Page3.getText();
        k++;
    }

    //test each link
    for (String t : linkTitles3) 
    {
            // Titles Click 
            driver.findElement(By.linkText(t)).click();
            System.out.println("\n"+ driver.getTitle());

            driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);

            if(driver.findElement(By.xpath(".//*[@id='d9c1cb30-3459-4246-919d-41c5fe23de2f']/div/div/article/div/ul[1]/li[3]/a")).isDisplayed())
            {
                driver.findElement(By.xpath(".//*[@id='d9c1cb30-3459-4246-919d-41c5fe23de2f']/div/div/article/div/ul[1]/li[3]/a")).click();     
                driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
                Thread.sleep(4000);  

                System.out.println(driver.findElement(By.xpath(".//*[@id='d9c1cb30-3459-4246-919d-41c5fe23de2f']/div/div/article/dl/dd[3]/a")).getText());
                System.out.println(driver.getCurrentUrl());
                driver.navigate().back();
                driver.navigate().back();
            }
            else
            {
                System.out.println("No Teaching Notes Present");
                driver.navigate().back();

            }
    }

ERROR : Exception in thread "main" org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"xpath","selector":".//*[@id='d9c1cb30-3459-4246-919d-41c5fe23de2f']/div/div/article/div/ul[1]/li[3]/a"}

Upvotes: 0

Views: 1002

Answers (1)

Sudharsan Selvaraj
Sudharsan Selvaraj

Reputation: 4832

Wrap the if/else part inside try catch block. Because selenium will through exception if no element with given locator is available in the page.

try{
if(driver.findElement(By.xpath(".//*[@id='d9c1cb30-3459-4246-919d-41c5fe23de2f']/div/div/article/div/ul[1]/li[3]/a")).isDisplayed())
        {
            driver.findElement(By.xpath(".//*[@id='d9c1cb30-3459-4246-919d-41c5fe23de2f']/div/div/article/div/ul[1]/li[3]/a")).click();     
            driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
            Thread.sleep(4000);  

            System.out.println(driver.findElement(By.xpath(".//*[@id='d9c1cb30-3459-4246-919d-41c5fe23de2f']/div/div/article/dl/dd[3]/a")).getText());
            System.out.println(driver.getCurrentUrl());
            driver.navigate().back();
            driver.navigate().back();
        }
        else
        {
            System.out.println("No Teaching Notes Present");
            driver.navigate().back();

        }
}catch(Exception e){
  System.out.println("No Teaching Notes Present");
            driver.navigate().back();
 }

otherwise you can also use isPresent() instead of isDisplayed()

Upvotes: 1

Related Questions