我有以下代码:
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()
似乎没有效果 - 程序仍然打印页面首次加载时的原始源代码(因此没有加载其他元素)。有谁知道出了什么问题吗?
最佳答案
向下滚动页面时会加载其他电影。如果您想加载全部或一定数量的电影,则必须不断向下滚动并等待。
简单的实现:
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()
等待可能应该通过 WebDriverWait
替换为显式等待。
关于javascript - 滚动到底部后获取动态加载的 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36702826/