0

On a webpage, we are having two links displayed with no other attribute than the link text. I want to make a page object class for a page.

Here the question is how I can specify the WebElement object declaration in page object class which uniquely identified the second instance of the links displayed.

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

for the above (just an example to get the idea), I want to get WebElement object for the second link using PageFactory.initElement(driver, this) statement

@FindBy(how = How.LINK_TEXT, using = "Link")
public static WebElement link;

I think the above will identify the first object only.

Guy
  • 46,488
  • 10
  • 44
  • 88
DishantB
  • 53
  • 5

3 Answers3

1

When you are locating a single element selenium will return the first matching element in the DOM. You can specify index if you use XPATH

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

You can also locate all the links and use index on the returned list

@FindBy(how = How.LINK_TEXT, using = "Link")
public static List<WebElement> links;

WebElement link = links.get(1);
Guy
  • 46,488
  • 10
  • 44
  • 88
0

You can uniquely identify second element with below Xpath.

"(//a[.='Link'])[2]"

OR

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

With href attribute

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

OR

"(//a[@href='a.html'])[last()]"   // work if you have 2 Link with same href
Muzzamil
  • 2,823
  • 2
  • 11
  • 23
0

Two elements with the HTML DOM can't be identical. They may appear with respect to the similar set of attributes but their position within the DOM Tree whill differ.

Presuming, the <html> node being the immediate ancestor of the child <a> nodes, to identify the WebElement with the second link using PageFactory.initElement(driver, this) and FindBy annotation you can use either of the following Locator Strategies:

  • 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;
    
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352