我有一个webElements列表,我需要循环并点击每个元素,但是因为每次单击刷新页面我都会收到StaleElementReferenceException。每个元素都如下所示:
<img src="images/english/edit.gif" border="0" height="24" width="47">
所以我使用递归方法点击每个webElement,然后将索引传递给下一个实例并刷新列表:
public int enterDescription(int place) { List descriptions = driver.findElements(By.cssSelector(img[src='images/english/edit.gif']));for (int index = 0; index < descriptions.size(); index++) { index = place; if(place==descriptions.size()) { return place; } else { descriptions.get(index).click(); enterDescription(place++); } } return place; }
这最初工作直到方法崩溃的完成条件,在达到结束条件时我需要立即终止所有实例。有什么想法吗?
答案 0 :(得分:0)
忽略你通过这种结构终止你希望终止的递归东西
public interface Terminatable {
void terminate();
}
public class Terminator {
private LinkedList<Terminatable> terminatables = new LinkedList<Terminatable>();
public void register(Terminatable terminatable) {
terminatables.offer(terminatable);
}
public void unregister(Terminatable terminatable) {
terminatables.remove(terminatable);
}
public void terminate() {
Terminatable terminatable = terminatables.poll();
while(terminatable != null) {
terminatable.terminate();
terminatable = terminatables.poll();
}
}
}
public class Worker implements terminatable {
private Terminator terminator;
public Worker(Terminator terminator) {
this.terminator = terminator;
terminator.register(this);
}
public void terminate() {
// do your termination stuff here
}
[...]
public void work() {
// do your work and start termination when you are finished
terminator.terminate();
}
}
如果您不再需要,请记住取消注册您的工人!
答案 1 :(得分:0)
你真的不需要递归才能做到这一点。您只需要在每次传递开始时通过for语句刷新您的描述。像这样:
public void enterDescription() {
int numberOfImages = driver.findElements(By.cssSelector(img[src='images/english/edit.gif'])).size();
for (int index = 0; index < numberOfImages; index++) {
List<WebElement> descriptions = driver.findElements(By.cssSelector(img[src='images/english/edit.gif']));
descriptions.get(index).click();
// Test something
// Do something to return to initial page
}
}