Problem statement
By default, most of us put a webdriverwait of 30 seconds and when finding an element using findelement or findelements method, if the element is not found within the wait limit, the code goes on to exception block. As a result there is no defined objectexists method in Selenium. This method is needed for implementing most of the page stability and AI logics
Solution 1
Most of us will put the findelement inside the try and catch. So, if the object not found, it can be captured in the exception block.
But the side effect: We have to wait till webdriverwait limit. Imagine waiting for 30 seconds just for finding if object exists or not
Solution 2
We often try to achieve some part objectexists by trying to implement IsVisible or IsEnabled alternatives. But both will not help us get rid of waiting till webdriverwait limit if the object really does not exist when the query is made.
Most workable solution
I found that attaching the Xpath with another Xpath that will always return results is the most viable and quickest solution here.
for e.g.: var elements = WebDriver.FindElements("//html[1] | //inut[@id='targetitem'")
In the above example, even though the 2nd part of the xpath (which is that of actual element) fails, the 1st part (//html[1]) will never fail so, the result will not wait till the wait limit.
We can loop through the elements list and first element which is of tag not html is usually the result
IWebElement eleTarget = null;
for(int i=0;i< 25;i++)
{
var list = WebDriver.FindElements("//html[1] | //input[@id='targetelement']");
foreach(var ele in list)
{
if(ele.TagName !="html")
{
eleTarget = ele;
break;
}
}
if(eleTarget != null)
{
break;
}
else
{
System.Threading.Thread.Sleep(500);
}
}
if(eleTarget == null)
{
Console.WriteLine("Item not found in 12.5 seconds");
}
Leave a Reply