在 Java 中使用 selenium 网络驱动程序自动无限滚动网页
Automate infinitely scrolling webpage using selenium web driver in Java
我正在尝试自动化网页,我需要一直滚动到页面底部并单击页脚。但是,我正在自动化的网页有无限滚动。有什么帮助吗?
public class practiceNG
{
WebDriver driver;
@BeforeTest
public void start()
{
System.setProperty("webdriver.chrome.driver", "Y:\Selenium\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("http://the-internet.herokuapp.com/");
}
@Test (priority = 3)
public void infiniteScroll() throws InterruptedException
{
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("window.scrollBy(0,200)", "");
driver.findElement(By.xpath(".//[@id=\'content\']/ul/li[23]/a")).click();
Thread.sleep(1000);
((JavascriptExecutor) driver).executeScript("window.scrollTo(0, document.body.scrollHeight)");
driver.findElement(By.xpath("//*[@id=\"page-footer\"]/div/div/a")).click();
}
@AfterTest
public void close()
{
driver.quit();
}
}
您可以使用以下代码
while(footerIsNotPresent()){
JavascriptExecutor jse = (JavascriptExecutor) driver;
jse.executeScript("window.scrollTo(0, document.body.scrollHeight);");
}
您可以将 footerIsNotPresent() 替换为您自己的代码,以检查是否到达页面底部。它会一直滚动直到页脚不存在。
我正在尝试自动化网页,我需要一直滚动到页面底部并单击页脚。但是,我正在自动化的网页有无限滚动。有什么帮助吗?
public class practiceNG
{
WebDriver driver;
@BeforeTest
public void start()
{
System.setProperty("webdriver.chrome.driver", "Y:\Selenium\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("http://the-internet.herokuapp.com/");
}
@Test (priority = 3)
public void infiniteScroll() throws InterruptedException
{
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("window.scrollBy(0,200)", "");
driver.findElement(By.xpath(".//[@id=\'content\']/ul/li[23]/a")).click();
Thread.sleep(1000);
((JavascriptExecutor) driver).executeScript("window.scrollTo(0, document.body.scrollHeight)");
driver.findElement(By.xpath("//*[@id=\"page-footer\"]/div/div/a")).click();
}
@AfterTest
public void close()
{
driver.quit();
}
}
您可以使用以下代码
while(footerIsNotPresent()){
JavascriptExecutor jse = (JavascriptExecutor) driver;
jse.executeScript("window.scrollTo(0, document.body.scrollHeight);");
}
您可以将 footerIsNotPresent() 替换为您自己的代码,以检查是否到达页面底部。它会一直滚动直到页脚不存在。