Reputation: 33361
I need to check if some element exists on the page or not.
I already saw this WebDriver: check if an element exists? issue but I'm wondering why not simply apply findElements().isEmpty
method?
I thought it would do the same work.
UPD Now I see findElements().isEmpty
works perfect so I'm just wondering why to look for other, much complex ways, while there is a straightforward method for that?
Upvotes: 2
Views: 8054
Reputation: 1
The best way that I found by limiting the scope of search for elements in the page for example this function search for any tag Name you want to get the text of those tags and store it in an ArrayList then all what you have to do is to match the element text that you want to prove not exist in the page with the ArrayList values. -if the element text not found in the array that means your test Pass: element not exist/display.. in the page
/**
* @params : tagName, elementText
* @desc: To check the Elements is not Exist in the page - by actual tagName for element and the expected element text
*/
public void verifyElementIsNotExistByTagNameAndElementText(String tagName, String elementText) {
ArrayList<String> arrList;
List<WebElement> listOfTags = driver.findElements(By.tagName(tagName));
arrList = listOfTags.stream().map(WebElement::getText).collect(Collectors.toCollection(ArrayList::new));
System.out.println(ConsoleColors.BLACK_BOLD+"All TagNames Text: "+arrList+ConsoleColors.RESET);
if (!arrList.contains(elementText)) {
System.out.println(ConsoleColors.GREEN_BOLD+"PASS: "+ConsoleColors.BLACK_BOLD+elementText+ConsoleColors.BLACK+" is not exist in the page"+ConsoleColors.RESET);
} else {
System.out.println(ConsoleColors.RED_BOLD+"FAIL: "+ConsoleColors.BLACK_BOLD+elementText+ConsoleColors.BLACK+" is exist in the page"+ConsoleColors.RESET);
}
}
Upvotes: 0
Reputation: 1
The below code works fine in case of the WebDriver
if(driver.findElements(By.xpath(xpath)).size()!=0)
{
...
}
But if we use WebElementFacade we can write some thing like below which is pretty much easier.
@FindBy(xpath = "xpathvalue")
private WebElementFacade element;
if(element.isPresent())
{
...
}
Upvotes: 0
Reputation: 1338
findElements returns a list of all elements matching a given selector. So you are using java's list built in isEmpty()
method here.
Upvotes: 0
Reputation: 2981
isEmpty()
is actually from the Java List
class, as findElements()
returns a List
of WebElements.
Upvotes: 2
Reputation: 3707
public static WebElement findElement(WebDriver driver, By selector, long timeOutInSeconds) {
WebDriverWait wait = new WebDriverWait(driver, timeOutInSeconds);
wait.until(ExpectedConditions.presenceOfElementLocated(selector));
return findElement(driver, selector);
}
public static WebElement findElementSafe(WebDriver driver, By selector, long timeOutInSeconds) {
try {
return findElement(driver, selector, timeOutInSeconds);
} catch (TimeoutException e) {
return null;
}
}
Upvotes: 0