【问题标题】:How to pause Selenium execution when progress bar is shown显示进度条时如何暂停 Selenium 执行
【发布时间】:2021-04-27 10:11:54
【问题描述】:

我有一个想要自动化的 Angular SPA 应用程序。当显示此进度条时:

<div _ngcontent-cln-c1="" class="ngx-loading-text center-center" style="top: calc(50% + 60px + 5px); color: white;">Loading...</div>

我想全局暂停 Java 代码的执行。如果这个 div 是可见的,是否可以以某种方式暂停 Selenium?

【问题讨论】:

  • 可能想尝试使用 WebDriverEventListeners:selenium.dev/selenium/docs/api/java/org/openqa/selenium/support/…
  • 能否请您告诉我如何全局配置它以等待Loading... 文本并暂停执行?
  • 配置以下选项/答案之一以使用 webdrivereventlistener(或 2 个?)运行取决于这可能出现的时间。它们是相当新的,所以我真的不知道它们的支持程度以及它们是否可以满足您的需求。您也可以将它们构建成一种“驱动程序”类,以便在任何驱动程序操作之前运行。构建适合您需求的架构。请务必考虑 loading... 元素加载/出现所需的时间。

标签: java selenium selenium-webdriver webdriverwait expected-condition


【解决方案1】:

您可以使用 webdriver 等待:

WebDriverWait wait = new WebDriverWait(driver,30);


wait.until(ExpectedConditions.stalenessOf(loadingelement)));

WebDriverWait wait = new WebDriverWait(driver,30);


wait.until(ExpectedConditions.invisibilityOf​(loadingelement)));

以上将等到加载元素不可见或陈旧(意味着修改或删除)

您还可以使用:

List<WebElement> elementName = driver.findElements(By.xpath("//div[@class=\"ngx-loading-text center-center\"]"));

while(elementlist.size()){
  Thread.sleep(1000)
  elementName = driver.findElements(By.xpath("//div[@class=\"ngx-loading-text center-center\"]"));
}

上面的代码会检查 findelements 列表是否为空 else wai 1 秒然后尝试再次查找,循环继续直到 size 为 0

【讨论】:

    【解决方案2】:

    invisibilityOf()

    invisibilityOf(WebElement element) 定义为:

    public static ExpectedCondition<java.lang.Boolean> invisibilityOf(WebElement element)
    
    An expectation for checking the element to be invisible
    

    这里的期望是,元素必须 present 以及 visible 作为前置条件,并且该方法将等待元素出现 隐形。此时值得一提的是,由于参数是 WebElement 类型,findElement(By by) 必须成功定位元素作为前提条件。因此NoSuchElementException 不能被忽略


    invisibilityOfElementLocated()

    invisibilityOfElementLocated(By locator) 定义为:

    public static ExpectedCondition<java.lang.Boolean> invisibilityOfElementLocated(By locator)
    
    An expectation for checking that an element is either invisible or not present on the DOM.
    

    这里的期望显然是元素在HTML DOM 中已经不可见不存在。在这种情况下,主要任务是元素的缺席,它甚至可能在 ExpectedCondition 被调用之前或在 timespan 期间发生,而 ExpectedCondition 处于活动状态。所以这里我们需要忽略NoSuchElementException作为强制措施。


    这个用例

    要暂停程序的执行,您需要诱导WebDriverWait,您可以使用以下任一Locator Strategies

    • 使用invisibilityOf()

      new WebDriverWait(driver, 20).until(ExpectedConditions.invisibilityOf(driver.findElement(By.xpath("//div[@class='ngx-loading-text center-center' and starts-with(., 'Loading')]"))));
      
    • 使用invisibilityOfElementLocated():

      new WebDriverWait(driver, 20).until(ExpectedConditions.invisibilityOfElementLocated(By.xpath("//div[@class='ngx-loading-text center-center' and starts-with(., 'Loading')]")));
      

    【讨论】:

      猜你喜欢
      • 2021-09-23
      • 1970-01-01
      • 2013-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多