Waiting for WebElements to load

Waiting for WebElements is very important while we try to automate the browsers.  Because, Some system might have slow network, due to the slow network WebElements might have appear late on the webpage.

While Selenium scripts are running, if the WebPage is not loaded to the particular wait time, test steps will fail if WebElements are not found.

For example, I have used the below code for my Qafreaks.com, The code does wait until the WebElement is loaded for the 'follow' button which appears on the web page top right of the corner.
'Follow' widget will appear after some seconds of the web page.  Once, follow widget is loaded, scripts will be able to print the WebElement result.

Code:
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Wait;
import org.openqa.selenium.support.ui.WebDriverWait;

public class WebDriverWaitMethod {
 
//WebDriver Declaration
private static WebDriver driver = null;
 
//Main Method
public static void main(String[] args) throws InterruptedException {
  
//Chrome Browser Driver Path
System.setProperty("webdriver.chrome.driver", "C:/Project1/lib/driver/chromedriver.exe");
  
//Invoke Chrome Browser
driver = new ChromeDriver();
  
//Open URL QaFreaks.com
driver.get("http://www.qafreaks.com/p/selenium-links.html");
 
//Load WebElement Until the present of Element Located
WebElement myDynamicElement = (new WebDriverWait(driver, 100))
.until(ExpectedConditions.presenceOfElementLocated(By.className("at-follow-label")));
  
System.out.println("Detected" + driver.findElement(By.className("at-follow-label")));
}
}
Output:
Starting ChromeDriver (v2.9.248315) on port 19677
Detected[[ChromeDriver: chrome on XP (a5f60c446eb5fb273b0834df23)] -> class name: at-follow-label]

No comments:

Post a Comment

Socialize It and Share the post with your friends
SOCIALIZE IT →
FOLLOW US →
SHARE IT →