我尝试通过 foreach 循环检索文本,按照页面顺序。流程是:它打印单行文本,一旦完成,它就会转到第二页并再次开始检索文本。问题是,它多次检索第一页的数据,有时是 2、3、4 次,如何控制它单次执行?
if (driver.findElement(By.xpath("//button[@ng-click='currentPage=currentPage+1']")).isEnabled()) {
int ilength = driver.findElements(By.xpath("//input[@ng-attr-id='{{item.attr}}']")).size();
Outer: for (int i1 = ilength; i1 > 0;) {
List<WebElement> findData = driver.findElements(By.xpath("//input[@ng-attr-id='{{item.attr}}']"));
for (WebElement webElement : findData) {
String printGroupName = webElement.getAttribute("value").toString();
System.out.println(printGroupName);
ilength--;
}
if (driver.findElement(By.xpath("//button[@ng-click='currentPage=currentPage+1']")).isEnabled()) {
action.moveToElement(driver.findElement(By.xpath("//button[@ng-click='currentPage=currentPage+1']"))).click().perform();
page.pagecallingUtility();
ilength = driver.findElements(By.xpath("//input[@ng-attr-id='{{item.attr}}']")).size();
} else {
break Outer;
}
}
} else {
List<WebElement> findAllGroupName = driver.findElements(By.xpath("//input[@ng-attr-id='{{item.attr}}']"));
for (WebElement webElement : findAllGroupName) {
String printGroupName = webElement.getAttribute("value").toString();
System.out.println(printGroupName);
}
}
最佳答案
您的循环可以简化如下。
boolean newPageOpened = true;
while (newPageOpened) {
List<WebElement> findData = driver.findElements(By.xpath("//input[@ng-attr-id='{{item.attr}}']"));
for (WebElement webElement : findData) {
if (webElement.isDisplayed()) {
String printGroupName = webElement.getAttribute("value").toString();
System.out.println(printGroupName);
}
}
WebElement nextButton = driver.findElement(By.xpath("//button[@ng-click='currentPage=currentPage+1']"));
if (nextButton.isEnabled()) {
action.moveToElement(nextButton).click().perform();
page.pagecallingUtility();
} else {
newPageOpened = false;
}
}
至于一遍遍打印第一页的内容,我怀疑当你打开第二页时,第一页的内容根本就隐藏在页面中了。因此,当您使用 driver.findElements(By.xpath("//input[@ng-attr-id='{{item.attr}}']"))
时,隐藏的首页元素是也发现了。简单的解决方案是在打印之前检查元素是否显示。
关于java - 如何在使用 Selenium 驱动程序执行 Foreach 循环时对其进行控制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50014590/