Test dynamically loaded content with Selenium Web Driver

Benjamin Ihrig picture Benjamin Ihrig · Oct 2, 2012 · Viewed 16.7k times · Source

I am working on a system that has a web based frontend that I am testing with Selenium. On one page the content is dynamically loaded when scrolling down (maybe you know that from Facebook's friend-list), because it is one of the requirements.

Scrolling down with Selenium Webdriver (I use Chrome) should be no problem via Javascript. But there is a problem with the dynamically added content. How can I make the Webdriver find those elements?

I tried the following to scroll down until no more content is loaded:

int oldSize = 0;
int newSize = 0;
do {
  driver.executeScript("window.scrollTo(0,document.body.scrollHeight)");
  newSize = driver.findElementsBy(By.cssSelector("selector").size();
} while(newSize > oldSize);

But though the page scrolls down the first time and some now content is loaded correctly, they will not be found by the drivers' findElementsBy(By) function.

Has someone ever faced this problem?? I'd be very glad if someone could help me figuring a solution for that!

Regards, Benjamin

Answer

StatusQuo picture StatusQuo · Oct 2, 2012

I would recommend using WebDriverWait with ExpectedConditons.

//scroll down with Javascript first
WebDriverWait wait = new WebDriverWait(driver, 30);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("selector")));
//interact with your element
element.click()

Take a look at the guidance provided by Selenium Official page: http://seleniumhq.org/docs/04_webdriver_advanced.html