Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

selenium

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

like image 408
Buras Avatar asked Sep 27 '13 19:09

Buras


People also ask

How do I click on a specific link in Selenium?

To click a link, we can use the link text locator which matches the text enclosed within the anchor tag. We can also use the partial link text locator which matches the text enclosed within the anchor tag partially. NoSuchElementException is thrown if there is no matching element found by both these locators.

Where is XPath for href link in Selenium?

This will get you the generic link: selenium. FindElement(By. XPath("xpath=//a[contains(@href,'listDetails.do')")).

Can we use HREF in Selenium?

We can click a href link with Selenium webdriver. There are multiple ways to achieve this. First of all we need to identify the link with the help of the locators like link text and partial link text. The link text locator identifies the element whose text matches with text enclosed within the anchor tag.


1 Answers

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

like image 195
ddavison Avatar answered Sep 29 '22 08:09

ddavison