滚动到底部后获取动态加载的HTML

时间:2016-04-18 19:34:10

标签: javascript java html selenium selenium-webdriver

我有以下代码:

import java.io.IOException;

import com.machinepublishers.jbrowserdriver.JBrowserDriver;
import com.machinepublishers.jbrowserdriver.Settings;
import com.machinepublishers.jbrowserdriver.Timezone; 

public class ReadMovies {

    public static void main(final String[] args) throws IOException {
        final JBrowserDriver driver = new JBrowserDriver(Settings.builder().timezone(Timezone.AMERICA_NEWYORK).build());
        driver.get("http://www.cinesift.com/#/");

        driver.executeScript("window.scrollTo(0, document.body.scrollHeight)");

        System.out.println(driver.getPageSource());

        driver.quit();
    }
}

但是,executeScript()似乎没有效果 - 程序仍然会在首次加载页面时打印原始源(因此没有加载其他元素)。有谁知道什么是错的?

1 个答案:

答案 0 :(得分:1)

向下滚动页面时会加载其他动画。如果要加载所有或一定数量的电影,则必须不断向下滚动并等待。

天真的实施:

 grep -E 'stopped: ([1-9]|[0-9]{2,})\.' file

int DESIRED_COUNT = 100; int currentCount = driver.findElements(By.cssSelector("#films .film")).size(); while (currentCount < DESIRED_COUNT) { driver.executeScript("window.scrollTo(0, document.body.scrollHeight)"); Thread.sleep(1000); currentCount = driver.findElements(By.cssSelector("#films .film")).size(); } // now get the page source System.out.println(driver.getPageSource()); 等待应该可以通过Thread.sleep()替换为显式等待。