Thursday, June 27, 2019

How check if an Element is present in Selenium WebDriver

How check if an Element is present in Selenium WebDriver(5 Ways)


1) To check if Element Present on WebPage:

Key: use idDisplayed() method
Below, the first block of code checks out the size of the element. Every Element in Selenium has a size. So, if the Size of the Element is zero, it means that the element is not present on the web
if( driver.findElement(By.cssSelector("a > font")).isDisplayed()){
System.out.println("Element is Visible");
}else{
System.out.println("Element is InVisible");
}
Key: use Not Null checks
Below, an Element is not NULL if it is present on the web page. Hence, in the second block of code above, once the if condition returns true(Element is not null), we have the output Element is present.
if(driver.findElement(By.xpath("value"))!= null){
System.out.println("Element is Present");
}else{
System.out.println("Element is Absent");
}
Also, 

2) To check if element is Visible on WebPage:

if( driver.findElement(By.cssSelector("a > font")).isDisplayed()){
System.out.println("Element is Visible");
}else{
System.out.println("Element is InVisible");
}
The isDisplayed() method comes handy when we need to check if an element is displayed on the webpage. If returns a boolean which can be useful to ascertain if the element on the web page is visible. We can use the if condition on the isDisplayed() method and decide on the navigation flow based on the element’s availability on the DOM.


3) To check if Element is Enabled on the WebPage:

if( driver.findElement(By.cssSelector("a > font")).isEnabled()){
System.out.println("Element is Enable");
}else{
System.out.println("Element is Disabled");
}
The isEnabled() method comes handy when we need to check if an element is enabled for clicking or performing some action on it, on the webpage. If returns a boolean which can be useful to ascertain if the element on the web page is ready for being interacted with(perform actions on it/use it in our script). We can use the if condition on the isEnabled() method as above and decide on the navigation flow based on the element being enabled on the DOM.

4) To check text present:

if(driver.getPageSource().contains("Text to check")){
System.out.println("Text is present");
}else{
System.out.println("Text is absent");
}
Most Elements on the Web page have an associated text. This element property can be used smartly to check if an element is present on the web page. Like, if the pageSource of the webpage contains the associated element’s text, we can infer that the element is present on the webpage.

No comments:

Post a Comment

Working with Pseudo elements in Selenium WebDriver

What are pseudo-elements? A CSS pseudo-element is a keyword added to a selector that lets you style a specific part of the selected elem...