为什么在selenium中使用元素列表是行不通的,但如果我使用WebDriver它就可以工作

问题描述 投票:1回答:1

我有这个代码,在我使用selenium的dom中找到div元素,以便在HTML页面中查找元素:

package com.indeni.automation.ui.model.alerts;

import com.indeni.automation.ui.model.PageElement;
import com.indeni.automation.ui.selenium.DriverWrapper;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;

import java.util.List;

public class FilterBar extends PageElement {

    private List<WebElement> edgeDropDownMenus = driver.findElements(By.cssSelector("div.dropdown-menu.left"));
    private List<WebElement> middleDropDownMenus = driver.findElements(By.cssSelector("div.combo-menu.left"));

    public FilterBar(DriverWrapper driver){
        super(driver);
    }

    public void clickOnIssuesDropDownMenu(){
        clickButton(edgeDropDownMenus.get(0));
    }
}

这是clickButton函数:

protected void clickButton(WebElement bthElm){
        bthElm.click();
        printClick(bthElm);
    }

我收到以下错误:

java.lang.IndexOutOfBoundsException: Index 0 out of bounds for length 0

但如果我使用以下代码行,它的工作原理是:

clickButton(driver.findElements(By.cssSelector("div.dropdown-menu.left")).get(0));

但我想使用第一个优雅的方式,但我无法弄清楚为什么我收到此错误消息以及如何解决它。

selenium-webdriver
1个回答
1
投票

我很遗憾地说第一种方法并不优雅。在初始化类时找到元素是错误的。初始化类时,这些元素不可用。所以列表基本上是空的。如果您尝试访问列表中的任何元素,它将抛出异常。

在第二种方法中,您可以在单击它之前找到该元素。那个时候它呈现,所以它有效。这是正确的方法。

如果你想要一些优雅的东西,试试这样的东西。使用FindBy,我们只在需要时找到元素。不是在初始化类时。这很优雅,也可以使用。

public class FilterBar extends PageElement {


    @FindBy(css = "div.dropdown-menu.left" )
    private List<WebElement> edgeDropDownMenus;

    @FindBy(css = "div.combo-menu.left")
    private List<WebElement> middleDropDownMenus;

    public FilterBar(DriverWrapper driver){
        super(driver);
        PageFactory.initElements(driver, this);
    }

    public void clickOnIssuesDropDownMenu(){
        clickButton(edgeDropDownMenus.get(0));
    }

}
© www.soinside.com 2019 - 2024. All rights reserved.