没有找到任何元素的页面对象模式和 driver.findElements

Page Object Pattern and driver.findElements without any element found

来自 wiki 文档 https://github.com/SeleniumHQ/selenium/wiki/PageFactory 我发现,如果脚本使用 eg.
找到了一些元素 @FindBy(id = "q") WebElement q;

句子:

 q.sendKeys(text);

相当于:

driver.findElement(By.id("q")).sendKeys(text);

但是我如何在 POM 中使用注释:

driver.findElements(By.id("q")).isEmpty() ?

目前我只使用纯 Selenium 而没有注释,例如

 if(!driver.findElements(By.id("q")).isEmpty()) {
    q.click }

当然,我可以使用try/cath,但是在POM中应该有一些Annotation for 'findElements'。

根据 The PageFactory Documentation 使用 PageFactory,您需要在 PageObject 上声明一些字段WebElementList,例如:

  • WebElement :

    @FindBy(how = How.ID, using = "foobar") WebElement foobar;
    
  • List<WebElement> :

    @FindBy(how = How.TAG_NAME, using = "a") List<WebElement> links;
    

所以PageFactory的设计是基于我们必须声明变量的原则,PageFactory会在页面上搜索与WebElement的字段名称匹配的元素在 class。它通过首先查找具有匹配 Locator Strategy.

的元素来执行此操作

因此,要根据 driver.findElements(By.id("q")).isEmpty() 在 POM 中实现 @FindBy 注释,您可以使用以下代码块:

@FindBy(how = How.TAG_NAME, using = "a") List<WebElement> links;

public void myFunction() 
{
    if(!links.isEmpty()) 
    {
        for(WebElement ele:links)
            ele.click();
    }
}

你要的不是Selenium WebDriver的东西。这是 Java.

isEmpty() 方法属于 List 接口。调用findElements()方法后返回List

如果您想使用 @FindBy 并检查 List 是否为空,请执行以下操作:

@FindBy(id = "q")
WebElement element;

@FindBy(id = "q")
List<WebElement> listOfElements;

public void someMethod() {
    //can't use `isEmpty()` on `element` because it's NOT a list
    listOfElements.isEmpty(); //that's how you can use it
}