How to click a link whose href has a certain substring in Selenium?

JavaSelenium

Java Problem Overview


The following is a bunch of links <a elements. ONLY one of them has a substring "long" as a value for the attribute href

<a class="c1" href= "very_lpng string" > name1 </a>
<a class="g2" href= "verylong string" > name2 </a>   // The one that I need
<a class="g4" href= "very ling string" > name3 </a>
<a class="g5g" href= "very ng string" > name4 </a>

...................

I need to click the link whose href has substring "long" in it. How can I do this?

PS: driver.findElement(By.partialLinkText("long")).click(); // b/c it chooses by the name

Java Solutions


Solution 1 - Java

> I need to click the link who's href has substring "long" in it. How can I do this?

With the beauty of CSS selectors.

your statement would be...

driver.findElement(By.cssSelector("a[href*='long']")).click();

This means, in english,

>Find me any 'a' elements, that have the href attribute, and that attribute contains 'long'

You can find a useful article about formulating your own selectors for automation effectively, as well as a list of all the other equality operators. contains, starts with, etc... You can find that at: http://ddavison.io/css/2014/02/18/effective-css-selectors.html

Solution 2 - Java

use driver.findElement(By.partialLinkText("long")).click();

Solution 3 - Java

You can do this:

//first get all the <a> elements
List<WebElement> linkList=driver.findElements(By.tagName("a"));

//now traverse over the list and check
for(int i=0 ; i<linkList.size() ; i++)
{
	if(linkList.get(i).getAttribute("href").contains("long"))
	{
		linkList.get(i).click();
		break;
	}
}

in this what we r doing is first we are finding all the <a> tags and storing them in a list.After that we are iterating the list one by one to find <a> tag whose href attribute contains long string. And then we click on that particular <a> tag and comes out of the loop.

Solution 4 - Java

With the help of xpath locator also, you can achieve the same.

Your statement would be:

driver.findElement(By.xpath(".//a[contains(@href,'long')]")).click();

And for clicking all the links contains long in the URL, you can use:-

List<WebElement> linksList = driver.findElements(By.xpath(".//a[contains(@href,'long')]"));

for (WebElement webElement : linksList){
         webElement.click();
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBurasView Question on Stackoverflow
Solution 1 - JavaddavisonView Answer on Stackoverflow
Solution 2 - Javart2800View Answer on Stackoverflow
Solution 3 - JavaPraveenView Answer on Stackoverflow
Solution 4 - JavaNitish KumarView Answer on Stackoverflow