Archit Arora
Archit Arora

Reputation: 2636

Select a Selenium element based on text in nested tags

Im new to Selenium. This is my HTML code -

<a href="#">
   <span>Print</span>
</a>

Using Selenium, I would like to find the element <a> that contains <span> and within the <span>, the text - "Print". There is only one such element on the page.

 driver.findElement(By.cssSelector("a[text()='Print']"))

The above code doesn't seem to work. How do I include <span> in the above code ?

The Jquery equivalent of what I am trying to achieve is - $( "a > span:contains('Print')" )

Please help!

Upvotes: 0

Views: 743

Answers (3)

KunduK
KunduK

Reputation: 33384

As mentioned OP there is no option yet in css selector to identify an element based on text value.

I would suggest use XPATH.

To identify the anchor tag based on child tag try following xpath options.

driver.findElement(By.xpath("//a[./span[text()='Print']]"))

OR

driver.findElement(By.xpath("//a[contains(.,'Print')]"))

Upvotes: 0

professorFreak
professorFreak

Reputation: 61

You can use Xpath to achieve this:

WebElement el = driver.findElement(By.xpath("//a/span[text()='Print']"))

To make it more robust, in case span is not the immediate child of the a tag and the text can have leading trailing spaces/characters you can use:

WebElement el = driver.findElement(By.xpath("//a//span[contains(text(),'Print')]"))

Upvotes: 1

Amit Jain
Amit Jain

Reputation: 4595

Something like this you can try

driver.findElement(By.tagName("a")).findElement(By.tagName("span")).getText();

Upvotes: 0

Related Questions