如何使用 Selenium 和 Java 通过 PageFactory 等待元素不可见

Mat*_*rše 5 java selenium pageobjects page-factory webdriverwait

有没有办法使用 PageFactory 注释等待 Selenium 中不存在的元素?

使用时:

@FindBy(css= '#loading-content')
WebElement pleaseWait;
Run Code Online (Sandbox Code Playgroud)

定位元素,然后:

wait.until(ExpectedConditions.invisibilityOfElementLocated(pleaseWait));
Run Code Online (Sandbox Code Playgroud)

我会得到:

org.opeqa.selenium.WebElement cannot be converted to org.openqa.selenium.By
Run Code Online (Sandbox Code Playgroud)

我可以使用以下方法完成我需要的操作:

wait.until(ExpectedConditions.invisibilityOfElementLocated(By.cssSelector('loading-content')));
Run Code Online (Sandbox Code Playgroud)

但是,我希望能够使用 PageFactory 注释以保持框架一致。有没有办法做到这一点?

Sam*_*ora 2

invisibilityOfElementLocated正在等待一个定位器,但您正在发送一个网络元素,这就是它抛出错误的原因。您可以使用以下命令检查 webelement 列表来执行该操作:

wait.until(ExpectedConditions.invisibilityOfAllElements(Arrays.asList(pleaseWait)));
Run Code Online (Sandbox Code Playgroud)

更新的答案:
如果您想检查该元素是否不存在于页面上,那么您可以检查其列表大小是否等于 0,因为当其未显示在 UI 上时,其列表大小将为 0。

您可以使用以下方法获取元素列表:

@FindBy(css='#loading-content')
List<WebElement> pleaseWait;
Run Code Online (Sandbox Code Playgroud)

您可以使用以下命令检查列表大小是否等于 0:

if(pleaseWait.size()==0){
     System.out.println("Element is not visible on the page");
     // Add the further code here
}
Run Code Online (Sandbox Code Playgroud)

这也不会给出 NoSuchElement 异常。