如何通过使用Selenium和Java的PageFactory等待元素的隐身

如何通过使用Selenium和Java的PageFactory等待元素的隐身

问题描述:

是否可以使用PageFactory批注来等待Selenium中不存在的元素?

Is there a way to wait for an element not present in Selenium using PageFactory annotations?

使用时:

@FindBy(css= '#loading-content')
WebElement pleaseWait;

找到元素,然后:

wait.until(ExpectedConditions.invisibilityOfElementLocated(pleaseWait));

我会得到:

org.opeqa.selenium.WebElement cannot be converted to org.openqa.selenium.By

我可以使用以下方法来做我需要做的事情:

I am able to do what I need by using:

wait.until(ExpectedConditions.invisibilityOfElementLocated(By.cssSelector('loading-content')));

但是,我希望能够使用PageFactory批注以保持框架的一致性.有办法吗?

However, I would like to be able to use the PageFactory annotations in order to keep the framework consistent. Is there a way to do this?

invisibilityOfElementLocated 需要一个定位器,但是您正在发送一个Web元素,这就是为什么它会引发错误.您可以通过使用以下方法检查Web元素列表来执行操作:

invisibilityOfElementLocated is expecting a locator but you are sending a web-element and that is why it is throwing an error. You can perform the operation by checking the webelement list by using:

wait.until(ExpectedConditions.invisibilityOfAllElements(Arrays.asList(pleaseWait)));

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

Updated Answer:
If you want to check that the element is not present on the page then you can check its list size is equal to 0 or not, as its list size will be 0 when its not displayed on the UI.

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

You can get the list of the element by using:

@FindBy(css='#loading-content')
List<WebElement> pleaseWait;

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

And you can check the list size equals to 0 by using:

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

这也不会给NoSuchElement异常.

And this would not give NoSuchElement exception as well.