user3729477 user3729477 - 23 days ago 6
C# Question

how to execute script when element is not found in selenium

WebElement Find=null;
Find=driver.findElement(By.xpath("//*[@id='headerapp']/div/div/ul/li[2]/a"));
if(Find!=null && Find.isDisplayed()){
Actions action=new Actions(driver);
action.moveToElement(Find).build().perform();
driver.findElement(By.xpath("//*[@id='headerapp']/div/div/ul/li[2]/ul/li[1]/a")).click();
driver.manage().timeouts().implicitlyWait(15000, TimeUnit.SECONDS);
}
Thread.sleep(2000);
WebElement mybuyers=null;
try{
mybuyers=driver.findElement(By.xpath("//a[contains(., 'My Buyers')]"));
if(mybuyers!=null && mybuyers.isDisplayed()){
Actions action=new Actions(driver);
action.moveToElement(mybuyers).build().perform();
mybuyers.click();
driver.manage().timeouts().implicitlyWait(15000, TimeUnit.SECONDS);
}
}catch(Exception e){
System.out.println("My Buyers link is not displayed");
}
finally{
driver.manage().timeouts().implicitlyWait(15000, TimeUnit.SECONDS);
}
Thread.sleep(2000);
WebElement mylisting=null;
try{
mylisting=driver.findElement(By.xpath("//a[contains(., 'My Listing')]"));
if(mylisting!=null && mylisting.isDisplayed()){
Actions action=new Actions(driver);
action.moveToElement(mylisting).build().perform();
mybuyers.click();
driver.manage().timeouts().implicitlyWait(15000, TimeUnit.SECONDS);
}
}catch(Exception e){
System.out.println("My Listing link is not displayed");
}
finally{
driver.manage().timeouts().implicitlyWait(15000, TimeUnit.SECONDS);

}



  • I am using the below code snippet to Verify the visibility of an Element. whenever the mybuyers element is not present then selenium is taking too much time and not continuing the next step.

  • In above script catch block is printing the message "My Buyers link is not displayed" but not moving to next steps of the script.



Can anyone please help me

Thanks,

Srinu

Answer

Use FindElements instead of FindElement like this:

 Boolean isMyBuyersPresent = driver.findElements(By.yourLocator).size() > 0

And

if(isMyBuyersPresent)
{
    //You can re-find as below, or refactor the code and 
    //create a list in the above snippet and grab the first element here

    mybuyers= driver.findElements(By.yourLocator)
}