How to verify element present or visible in selenium 2 (Selenium WebDriver)
I used java print statements for easy understanding.
-
To check Element Present:
if(driver.findElements(By.xpath("value")).size() != 0){ System.out.println("Element is Present"); }else{ System.out.println("Element is Absent"); }
Or
if(driver.findElement(By.xpath("value"))!= null){ System.out.println("Element is Present"); }else{ System.out.println("Element is Absent"); }
-
To check Visible:
if( driver.findElement(By.cssSelector("a > font")).isDisplayed()){ System.out.println("Element is Visible"); }else{ System.out.println("Element is InVisible"); }
-
To check Enable:
if( driver.findElement(By.cssSelector("a > font")).isEnabled()){ System.out.println("Element is Enable"); }else{ System.out.println("Element is Disabled"); }
-
To check text present
if(driver.getPageSource().contains("Text to check")){ System.out.println("Text is present"); }else{ System.out.println("Text is absent"); }
You could try something like:
WebElement rxBtn = driver.findElement(By.className("icon-rx"));
WebElement otcBtn = driver.findElement(By.className("icon-otc"));
WebElement herbBtn = driver.findElement(By.className("icon-herb"));
Assert.assertEquals(true, rxBtn.isDisplayed());
Assert.assertEquals(true, otcBtn.isDisplayed());
Assert.assertEquals(true, herbBtn.isDisplayed());
This is just an example. Basically you declare and define the WebElement variables you wish to use and then Assert
whether or not they are displayed. This is using TestNG Assertions.
Here is my Java code for Selenium WebDriver. Write the following method and call it during assertion:
protected boolean isElementPresent(By by){
try{
driver.findElement(by);
return true;
}
catch(NoSuchElementException e){
return false;
}
}
Try using below code:
private enum ElementStatus{
VISIBLE,
NOTVISIBLE,
ENABLED,
NOTENABLED,
PRESENT,
NOTPRESENT
}
private ElementStatus isElementVisible(WebDriver driver, By by,ElementStatus getStatus){
try{
if(getStatus.equals(ElementStatus.ENABLED)){
if(driver.findElement(by).isEnabled())
return ElementStatus.ENABLED;
return ElementStatus.NOTENABLED;
}
if(getStatus.equals(ElementStatus.VISIBLE)){
if(driver.findElement(by).isDisplayed())
return ElementStatus.VISIBLE;
return ElementStatus.NOTVISIBLE;
}
return ElementStatus.PRESENT;
}catch(org.openqa.selenium.NoSuchElementException nse){
return ElementStatus.NOTPRESENT;
}
}
webDriver.findElement(By.xpath("//*[@id='element']")).isDisplayed();