如何使用 PageFactory.initElement(driver, this) 的索引号从 DOM 中识别两个相同的元素?

How to use index number with PageFactory.initElement(driver, this) to identify two identical elements from the DOM?

在网页上,我们显示了两个 link,除了 link 文本外没有其他属性。我想为一个页面创建一个页面对象 class。

这里的问题是如何在页面对象 class 中指定 WebElement 对象声明,它唯一标识显示的 link 的第二个实例。

<html>
  <a href="a.html">Link</a>
  <a href="a.html">Link</a>
</html>

对于上述(只是一个例子来理解),我想使用 PageFactory.initElement(driver, this) 语句

为第二个 link 获取 WebElement 对象
@FindBy(how = How.LINK_TEXT, using = "Link")
public static WebElement link;

我认为以上只会识别第一个对象。

当您定位单个元素时,selenium 将 return 第一个匹配的元素 DOM。如果使用 XPATH

则可以指定索引
@FindBy(how = How.XPATH, using = "//a[.='Link'][2]")
public static WebElement link;

您还可以在 returned 列表

上找到所有链接并使用索引
@FindBy(how = How.LINK_TEXT, using = "Link")
public static List<WebElement> links;

WebElement link = links.get(1);

您可以使用以下 Xpath.

唯一标识第二个元素
"(//a[.='Link'])[2]"

"(//a[.='Link'])[last()]"   //work if you have 2 Link with innerText ‘Link’

有href属性

"(//a[@href='a.html'])[2]"

"(//a[@href='a.html'])[last()]"   // work if you have 2 Link with same href

具有HTML DOM can't be identical. They may appear with respect to the similar set of attributes but their position within the DOM Tree的两个元素会有所不同。

假设 <html> 节点是子 <a> 节点的直接祖先,用第二个 link 识别 WebElement使用 PageFactory.initElement(driver, this)FindBy annotation you can use either of the following :

  • cssSelector:

    @FindBy(id = "html a:nth-of-type(2)")
    public static WebElement link;
    
  • xpath:

    @FindBy(how = How.XPATH, using = "//html//following::a[2]")
    public static WebElement link;