Home > other >  XPath find element by position of different element
XPath find element by position of different element

Time:12-13

Example html:

<table>
    <thead>
        <tr>
            <td ></td>
            <td ></td>
            <td ></td>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>1</td>
            <td>2</td>
            <td>3</td>
        </tr>
        <tr>
            <td>4</td>
            <td>5</td>
            <td>6</td>
        </tr>
    </tbody>
</table>

Problem

I have row position (//tbody/tr[X]) and header class (//thead//td[@])

I want to find table data cell using row and column

For example <td>5</td> can be located by //tbody/tr[2] and //thead//td[@]

Pseudo-xpath:

//tbody/tr[2]/td[position() = //thead//td[@]::position()]


I was tweaking with ancestor:: axis but it was dead end.

Any ideas how to write it properly?

CodePudding user response:

Try to use this XPath to select required node:

//tbody/tr[2]/td[position() = count(//thead/tr/td[@]/preceding-sibling::*)   1]

Instead of position we're checking the count of preceding siblings 1

CodePudding user response:

How do you locate multiple elements with the same XPath? If an xpath refers multiple elements on the DOM, It should be surrounded by brackets first () and then use numbering. if the xpath refers 4 elements in DOM and you need 3rd element then working xpath is common x path

  • Related