How to find a link with selenium?

The question is: How to find a link with Selenium JAVA API in the following scenario:

I wrote this method, I tried to use the xpaths match function:

public void clickOnLink(String sub_hrefText){
    String xpath = String.format("a[matches(@href,'%s')]",sub_hrefText);
    browser.findElements(By.xpath(xpath)).get(0).click();
}

But I got an exception:

InvalidSelectorException

Upvotes: 1

Views: 750

Answers (1)

paul trmbrth
paul trmbrth

Reputation: 20748

You say

I know some unique information about (substring) the href of the link I want to click on

so you can use XPath 1.0 function contains(haystack, needle) (see W3C XPath spec).

You also need a // or -- safer -- .// at the beginning of your expression to also select descendant a elements of the context node (root node in your case) further down the document tree, and not only direct children a nodes.

This gives us:

public void clickOnLink(String sub_hrefText){
    String xpath = String.format(".//a[contains(@href, '%s')]",sub_hrefText);
    browser.findElements(By.xpath(xpath)).get(0).click();
}

Upvotes: 1

Related Questions