如何使用Selenium webdriver查找具有相同CSS类的第二个值

时间:2014-04-30 09:12:26

标签: java css selenium webdriver

我想从li(它看起来像一个下拉列表,但它不是)中选择第二个值(在我的例子中,Bellevue)。这是一个截图:

enter image description here

我正在使用Page Objects,我正在使用@FindBy annonations来处理元素。这是我试过的:

@FindBy(how=How.CSS,using = "a[id^='ui-id-'][1]")

我收到错误:

The given selector a[id*='ui-id-'](1) is either invalid or does not result in a WebElement

或使用

@FindBy(how=How.CSS,using = "a[id^='ui-id-']"[1])`

我收到错误:

the type of expression must be an array but it resolved to string`.

如果我使用它,它会起作用:

WebElement value = driver.findElements(By.cssSelector("a[id^='ui-id']")).get(3);

value.click();

但我必须使用@FindBy而我无法使用get(3)方法。

3 个答案:

答案 0 :(得分:1)

您可以创建一些方法来访问所需的元素,而不使用FindBy注释定义的Web元素。例如

public void yourMethod(WebDriver driver) {
   WebElement value = driver.findElements(By.cssSelector("a[id^='ui-id']")).get(3); 
   value.click();
}

答案 1 :(得分:1)

IIRC,您可以使用XPath执行以下操作: @FindBy(how = How.XPATH,using ="(// a [contains(@class,' ui-id - ')])[2]") 其中final [2]指定前一个XPath返回的第二个元素。

(抱歉,我在记忆中工作 - 我还没有测试过这个特定的XPath)

答案 2 :(得分:1)

您无法在CSS选择器中使用[]索引元素。

以下是您可能想要尝试的内容:

@FindBy(how=How.CSS,using = "li.ui-menu-item:nth-of-type(2) > a[id^='ui-id-']")

或者使用XPath

@FindBy(how=How.XPATH,using = "(//a[starts-with(@id, 'ui-id-')])[2]")