以下是一个使用Java Selenium库实现网页自动翻页的代码:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
public class PageFlipper {
public static void main(String[] args) {
// 设置Chrome驱动的路径
System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver");
// 创建一个ChromeDriver实例
WebDriver driver = new ChromeDriver();
// 打开目标网页
driver.get("http://example.com");
// 获取页面上的"下一页"按钮
WebElement nextPageButton = driver.findElement(By.xpath("//button[@class='next-page']"));
// 循环点击"下一页"按钮,直到没有下一页为止
while (nextPageButton.isDisplayed()) {
// 点击"下一页"按钮
Actions actions = new Actions(driver);
actions.moveToElement(nextPageButton).click().perform();
// 等待一段时间,让页面加载完毕
Thread.sleep(5000);
// 获取新的"下一页"按钮
nextPageButton = driver.findElement(By.xpath("//button[@class='next-page']"));
}
// 关闭浏览器
driver.quit();
}
}
该代码使用ChromeDriver打开目标网页,并不断点击页面上的"下一页"按钮,直到没有下一页为止。在每次点击按钮之后,程序会等待5秒钟,让页面加载完毕。你可以根据自己的需要修改等待时间。