问题描述
我有一个想要自动化的 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?
解决方法
你可以使用 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 列表是否为空,否则 wai 1 秒,然后再次尝试查找,循环继续直到大小为 0
,invisibilityOf()
invisibilityOf(WebElement element)
定义为:
public static ExpectedCondition<java.lang.Boolean> invisibilityOf(WebElement element)
An expectation for checking the element to be invisible
这里的期望是,元素必须存在以及可见作为前提条件,并且该方法将等待元素看不见。在这一点上值得一提的是,由于参数是 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 被调用之前或在 时间跨度 期间发生,而 >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')]")));