【问题标题】:Page Object Pattern and driver.findElements without any element found没有找到任何元素的页面对象模式和 driver.findElements
【发布时间】:2018-03-09 12:15:40
【问题描述】:

从 wiki 文档 https://github.com/SeleniumHQ/selenium/wiki/PageFactory 我发现,如果脚本使用例如找到了一些元素。
@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'。

【问题讨论】:

  • 检查你的元素是否为空。

标签: java selenium selenium-webdriver pageobjects


【解决方案1】:

您要求的不是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
}

【讨论】:

    【解决方案2】:

    根据The PageFactory Documentation 要使用PageFactory,您需要在PageObject 上声明一些字段,这些字段可以是WebElement 或列表,例如:

    • WebElement

      @FindBy(how = How.ID, using = "foobar") WebElement foobar;
      
    • List&lt;WebElement&gt;

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

    所以 PageFactory 的设计是基于我们必须声明变量的原则,并且 PageFactory 将在页面上搜索与类中 WebElement 的字段名称匹配的元素。它通过首先查找具有匹配 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();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-01
      相关资源
      最近更新 更多