我需要在单击下一个按钮的同时一页一页地解析。我默认情况下连接到第一页,并解析到该页的最后一个元素:
driver.get("https://www.scimagojr.com/journalrank.php?country=UA&page=1");
我正在从首页上获取所有元素:
WebElement tableId = driver.findElement(By.tagName("table"));
List<WebElement> trElements = tableId.findElements(By.xpath("./tbody/tr"));
最后尝试检查下一个按钮是否可单击,然后从当前页面和其他剩余页面(如果存在)进行解析:
WebElement nextButton = driver.findElement(By.xpath("//img[contains(@title,'next')]"));
if(isClickable(nextButton, driver)) {
for (int id = 1; id <= trElements.size(); id++) {
for (WebElement element : trElements) {
//...
id++;
}
}
} else {
nextButton.click();
}
[当我浏览当前第一页的循环时-一切都很好,但是如果需要,我需要检查下一个按钮以再次解析另一页。
isClickable()
方法看起来像:
public static boolean isClickable(WebElement el, WebDriver driver) {
try {
WebDriverWait wait = new WebDriverWait(driver, 1);
wait.until(ExpectedConditions.elementToBeClickable(el));
return true;
} catch (Exception e) {
return false;
}
}
完成element.click();之后您的DOM被重建,因此之后让您的trElement保持陈旧的元素。
driver.get("https://www.scimagojr.com/journalrank.php?country=UA&page=1");
List<Journal> journalList = new ArrayList<>();
String numberOfElementsInPage = driver.findElementByXPath("(//div[@class='pagination'])[1]").getText();
String[] str = numberOfElementsInPage.split(" ");
String abc = str[4];
int countAllOfElements = Integer.parseInt(abc);
int countOfPages = (int) Math.ceil(countAllOfElements/50.0);
for (int i = 0; i < countOfPages; i++) {
WebElement tableId = driver.findElement(By.tagName("table"));
List<WebElement> trElements = tableId.findElements(By.xpath("./tbody/tr"));
for (int id = 1; id <= trElements.size(); id++) {
for (WebElement element : trElements) {
String title = element.findElement(By.xpath("./td[2]/a")).getText();
String country = "Ukraine";
journalList.add(new Journal(id, title, country));
id++;
}
}
WebElement element = driver.findElementByXPath("(//div[@class='pagination_buttons']/a)[2]");
element.click();
}
因此,我将可以在每页中更改的动态元素放入循环内以使其起作用。