【问题标题】:How to Loop Thread.sleep() statement , until Specified Element Found in Selenium Webdriver using Java如何循环 Thread.sleep() 语句,直到使用 Java 在 Selenium Webdriver 中找到指定元素
【发布时间】:2015-07-06 15:48:05
【问题描述】:

我想循环 Thread.sleep() 语句,直到找到指定的元素,我不想在 Thread.sleep() 语句中给出指定的时间,而不是我想循环 thread.sleep。所以它应该每秒检查一次元素,如果找到了元素,那么它应该打破循环。

有人可以帮我吗??

【问题讨论】:

  • 我不想在 Thread.sleep()每秒 中给出指定的时间。你想发生什么,究竟
  • 我已经删除了 multithreading 标签,因为它似乎不相关。

标签: java selenium


【解决方案1】:

如果您想等待元素出现或可见,请使用 WebDriverWaitExpectedConditions

Wait 将忽略遇到的 NotFoundException 实例 (抛出)默认情况下在“直到”条件下,并立即 传播所有其他人。您可以通过调用将更多内容添加到忽略列表中 忽略(添加例外)。

 WebDriverWait wait = new WebDriverWait(driver, 60);//timeout in Seconds
 wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("xpath"))).click();

【讨论】:

  • 感谢 madhan,但我已经通过使用 webdriver wait 以及所有可能的六种方法进行了检查,仍然无法正常工作,所以我想为此使用 thread.sleep,你有解决方案吗循环thread.sleep()???
  • @SumanthUrs 将等待时间增加到更多秒,例如 120 秒或 240 秒。为什么还要 Thread.Sleep
  • webdriver 等待不起作用,所以我正在使用 thread.sleep(),假设我给了 5 秒的时间,如果在 3 秒内找到元素,那么它应该跳过剩余的 2 秒并执行行动。它不应该等待 5 秒,所以我想循环条件.. 有什么解决方案吗?而不是 webdriver 等待
  • Webdriver 等待工作喜欢这样,只有在找到元素后它才会继续。它不会一直等待
  • @SumanthUrs 你有没有检查过元素是否存在于框架或其他东西中
【解决方案2】:

为什么不

            while(!howeverYouWantToCheckIfFound){
            try{
             thread.sleep(1000);}Catch(exception e){}
            }

【讨论】:

  • 因为它不可编译。
  • 哇,你是如何检查文件的。我的意思是什么在这里不起作用?
【解决方案3】:

稍微改进@Madhan 的答案,您还可以设置检查元素状态之间的睡眠间隔。这样做:

WebDriverWait wait = new WebDriverWait(getDriver(), TIME_OUT, TIME_TO_SLEEP);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("XPATH")));

【讨论】:

    【解决方案4】:

    我个人喜欢FluentWaitExpectedCondition。可以使用 ignoring amd pollingEvery 方法很好地配置它

    protected <T> T waitFor(ExpectedCondition<T> condition, String errorMessage) {
    Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
                                 .withTimeout(10, SECONDS)
                                 .ignoring(NullPointerException.class)
                                 .ignoring(StaleElementReferenceException.class)
                                 .ignoring(NoSuchElementException.class)
                                 .ignoring(ElementNotVisibleException.class)
                                 .ignoring(WebDriverException.class)
                                 .pollingEvery(100, MILLISECONDS)
                                 .withMessage(errorMessage);
    T result = wait.until(condition);
    return result;
    }  
    

    可以这样使用:

    waitFor(ExpectedConditions.elementToBeClickable(webElement),"Cannot click webElement");
    

    【讨论】:

      猜你喜欢
      • 2014-10-02
      • 1970-01-01
      • 2016-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多