Selenium webdriver 为什么要在selenium won';不起作用,但如果我使用WebDriver,它会起作用

Selenium webdriver 为什么要在selenium won';不起作用,但如果我使用WebDriver,它会起作用,selenium-webdriver,Selenium Webdriver,我有以下代码,用于在我使用selenium查找HTML页面中元素的dom中查找div元素: 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查找HTML页面中元素的dom中查找div元素:

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));
    }
}
我得到以下错误:

java.lang.IndexOutOfBoundsException: Index 0 out of bounds for length 0
但如果我使用的是以下代码行,那么它是有效的:

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

但是我想使用第一种优雅的方式,但是我不明白为什么我会收到这个错误消息以及如何修复它

很抱歉,第一种方法并不优雅。初始化类时查找元素是错误的。初始化类时,这些元素不可用。所以这个列表基本上是空的。如果您试图访问列表中的任何元素,它将抛出异常

在第二种方法中,在单击元素之前找到它。那一次它出现了,所以它起作用了。这是正确的做法

如果你想要优雅的东西,试试这样的。使用
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));
    }

}
public类FilterBar扩展了PageElement{
@FindBy(css=“div.dropdown-menu.left”)
私有列表edgedropdown菜单;
@FindBy(css=“div.combo-menu.left”)
私有列表下拉菜单;
公共滤清器杆(驾驶员振打器驾驶员){
超级司机;
PageFactory.initElements(驱动程序,this);
}
公共作废clickOnIssuesDropDownMenu(){
单击按钮(EdgeDropDownMenu.get(0));
}
}

我同意!谢谢你的详细解释。
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));
    }

}