【问题标题】:Recursion: Terminating all instances upon reaching end condition递归:在达到结束条件时终止所有实例
【发布时间】:2013-04-19 10:22:28
【问题描述】:

我有一个 webElements 列表,我需要遍历并单击每个元素,但是因为每次单击都会刷新页面,所以我会收到 StaleElementReferenceException。每个元素如下所示:

<img src="images/english/edit.gif" border="0" height="24" width="47">

所以我使用递归方法点击每个 webElement 然后将索引传递给下一个实例并刷新列表:


public int enterDescription(int place) { 列表描述 = 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; }

这最初一直有效,直到方法崩溃时的完成条件,达到结束条件后,我需要立即终止所有实例。有什么想法吗?

【问题讨论】:

  • 为什么需要递归呢?这是家庭作业吗?
  • 不,不是,如果有其他方法请指教。
  • 我猜你可以使用一个简单的循环。
  • 在它抛出 StaleElementReferenceException 之前我已经尝试过了
  • 递归对此无济于事。我认为你必须检查你的元素是否过时。

标签: java selenium recursion webdriver


【解决方案1】:

您实际上并不需要递归来执行此操作。您只需要在每次通过 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
        }
    } 

【讨论】:

    【解决方案2】:

    忽略递归的东西,你实现了用这个结构终止的愿望

    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();
        }
    }
    

    如果您不再需要他们,请记住取消注册您的工人!

    【讨论】:

      猜你喜欢
      • 2013-10-29
      • 2021-03-22
      • 1970-01-01
      • 1970-01-01
      • 2019-07-03
      • 1970-01-01
      • 2018-10-31
      • 2011-08-03
      • 2021-11-15
      相关资源
      最近更新 更多