【问题标题】:Selenium: How to locate dynamic element like notification messagesSelenium:如何定位动态元素,如通知消息
【发布时间】:2012-10-08 18:57:40
【问题描述】:

我正在使用 Selenium 和 Web 驱动程序。

我有一张要在灯箱中填写的表格。现在,当我单击“提交”时。该灯箱关闭,并在页面顶部生成一个简单的通知,该通知会在几秒钟后消失。

现在我的问题是:当我这样做时

driver.findElement(By.xpath(".//*[@id='createCaseBtn']")).click(); // x-path of submit button

我应该如何检查该通知消息是否出现在 UI 上。

因为当我这样做时

driver.findElement(By.xpath(".//*[@id='easyNotification']")).getText(); // x-path of easyNotification message

我向我展示了无法找到逻辑上正确的元素,因为当时 UI 上不存在通知消息。只有在完成 AJAX 请求(用于提交表单)之后,消息才会出现在 UI 上。

请帮忙!!!!

谢谢

【问题讨论】:

    标签: selenium selenium-webdriver xpath


    【解决方案1】:

    已使用显式等待。对我来说效果很好:

    显式等待是您定义的代码,用于等待特定条件发生,然后再继续执行代码。最坏的情况是 Thread.sleep(),它将条件设置为要等待的确切时间段。提供了一些方便的方法来帮助您编写只等待所需时间的代码。 WebDriverWait 与 ExpectedCondition 结合使用是实现此目的的一种方式。

    WebDriverWait wait = new WebDriverWait(driver, 10);
    WebElement element = wait.until(
        ExpectedConditions.visibilityOfElementLocated(By.id(".//*[@id='easyNotification']")));
    

    【讨论】:

      【解决方案2】:

      好吧。当我处理 AJAX 时,我总是使用流利的等待方法。 假设您有点击提交按钮后出现的消息定位器:

      String xPathMessage= ".//*[@id='easyNotification']"; 
      
          public WebElement fluentWait(final By locator){
                  Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
                          .withTimeout(30, TimeUnit.SECONDS)
                          .pollingEvery(5, TimeUnit.SECONDS)
                          .ignoring(NoSuchElementException.class);
      
                  WebElement foo = wait.until(
          new Function<WebDriver, WebElement>() {
                      public WebElement apply(WebDriver driver) {
                                  return driver.findElement(locator);
                          }
                          }
          );
                                     return  foo;              }     ;
      
      //simply call the method:
      String text=fluentWait(By.xpath(xPathMessage)).getText();
      

      来自流畅等待的文档: Wait 接口的一个实现,它可以动态配置其超时和轮询间隔。 每个 FluentWait 实例定义等待条件的最长时间,以及检查条件的频率。此外,用户可以将等待配置为在等待时忽略特定类型的异常,例如在页面上搜索元素时的 NoSuchElementExceptions。

      上述方法与isElementPresent配对也不错:

      public bool isElementPresent(By selector)
      {
          return driver.FindElements(selector).Any();
      }
      

      或者那个:

      public bool isElementPresent(By selector)
      {
          return driver.FindElements(selector).size()>0;
      }
      

      希望这对你有用

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-08-08
        • 2021-05-18
        • 2017-08-24
        • 1970-01-01
        • 2019-08-08
        • 1970-01-01
        • 2022-11-14
        • 1970-01-01
        相关资源
        最近更新 更多