How a write a common XPath for same text displayed for different HTML tags?

Viewed 64

I want to write a common XPath for the result displayed for my searched text 'Automation Server'

The same text is displayed for td HTML tags as well as for div html tags as shown below, and I wrote XPath as below based on my understanding by going through different article

displayed_text = //td[contains(text(),'Automation Server') or div[contains(text(),' Automation Server ')]

<td role="cell" mat-cell="" class="mat-cell cdk-cell cdk-column-siteName mat-column-siteName ng-star-inserted">Automation Server</td>

<div class="change-list-value ng-star-inserted"> Automation Server </div>
4 Answers

The operator you are looking for in XPath is |. It is a union operator and will return both sets of elements.

The XPath you are looking for is

//td[contains(text(),'Automation Server')] | //div[contains(text(),'Automation Server')]

This XPath,

//*[self::td or self::div][text()[normalize-space()='Automation Server']]

will select all td or div elements with an immediate text node whose normalize string value equals 'Automation Server'.

Cautions regarding other answers here

A few alternatives to JeffC answer, using common properties for both:

1. use the * as a wildcard for any element:

//*[contains(@class,'ng-star-inserted') and normalize-space(text())='Automation Server']

2. use in addition the local-name() function to narrow down the names of the elements:

//*[local-name()[.='td' or .='div']][contains(@class,'ng-star-inserted') and normalize-space(text())='Automation Server']

The normalize-space() function can be used to clean-up the optional white space, so a = operator can be used.

You could use the following XPath to test the local-name() of the element in a predicate and whether it's text() contains the phrase:

//*[(local-name() = "td" or local-name() = "div") and contains(text(), "Automation Server")]
Related