0

For example if we have an xml as follows:

<tr> <th>LION</th> <th>TIGER</th> <th>CHEETAH</th> <th>GIRAFFE</th> <th>BEAR</th> </tr> 

and I wanted to select the xpath element for GIRAFFE... how would (using xpath) I be able to tell which element under the GIRAFFE element is? Obviously, by looking at the xml, it is //tr/th[4] .... but is there a way I can use xpath to determine that it is the 4th element under ??

1
  • Is there some reason you can't just use //th[.='GIRAFFE'] to select the element? Commented Feb 28, 2019 at 22:06

2 Answers 2

2

Not entirely sure what you're asking, but perhaps one of these XPaths will help...


This XPath expression,

count(/tr/th[.="GIRAFFE"]/preceding-sibling::th)+1 

will evaluate to

4 

indicating that the GIRAFFE th element is the 4th th sibling element.


This XPath,

/tr/th[.="GIRAFFE"] 

will select the GIRAFFE th by virtue of its contents.


This XPath,

/tr/th[.="CHEETAH"]/following-sibling::th[1] 

will select the GIRAFFE th by virtue of its position after the CHEETAH th.

Sign up to request clarification or add additional context in comments.

Comments

0

If you want to select column element by header text in rows and use it in Selenium, here some examples:

Example of HTML:

<table> <thead> <tr> <th>LION</th> <th>TIGER</th> <th>CHEETAH</th> <th>GIRAFFE</th> <th>BEAR</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>2</td> <td>3</td> <td>4</td> <td>5</td> </tr> <tr> <td>1</td> <td>2</td> <td>3</td> <td>4</td> <td>5</td> </tr> </tbody> </table> 

XPATH for Selenium usage:

//table/tbody/tr/td[count(//table//th[.="GIRAFFE"]/preceding::th)+1] 

Selenium Java usage example:

String animalName = "GIRAFFE"; WebElement element = driver.findElement(By.xpath("//table/tbody/tr/td[count(//table//th[.='" + animalName + "']/preceding::th)+1]")); WebElement animalElementFromRow1 = driver.findElement(By.xpath("//table/tbody/tr[1]/td[count(//table//th[.='" + animalName + "']/preceding::th)+1]")); WebElement animalElementFromRow2 = driver.findElement(By.xpath("//table/tbody/tr[2]/td[count(//table//th[.='" + animalName + "']/preceding::th)+1]")); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.