0

Example Table Column

List<WebElement> clmnValue = driver.fintElements(By.xpath("//tbody/tr/td[1]"));

I'm trying to crate xpath for "Brand Name" which will store all the value under the "Brand Name" .. each time When i refresh "Brand Name" move to another column[its Dynamic not stay in 1column] but name remain unchanged. Need Help to crate xpath which will store all the Brand Name value in to the list. Thank you all.

Forensic_07
  • 1,125
  • 1
  • 6
  • 10
AR Rahman
  • 23
  • 7

1 Answers1

1

Assuming your input looks something like this.

<tbody>
    <tr>
        <th>Brand Name</th>
        <th>Price</th>
        <th>Discount</th>
    </tr>
    <tr>
        <td>Apple</td>
        <td></td>
        <td></td>
    </tr>
    <tr>
        <td>Samsung</td>
        <td></td>
        <td></td>
    </tr>
    <tr>
        <td>LG</td>
        <td></td>
        <td></td>
    </tr>
    <tr>
        <td>Motorolla</td>
        <td></td>
        <td></td>
    </tr>
</tbody>

Starting from this answer:

Find position of a node using xpath

We can count which position the desired column is in:

count(//tbody/tr/th[contains(., "Brand Name")]/preceding-sibling::th) + 1

Then we can then substitute it for the 1 in your example, creating an xpath that selects every cell in a row at that same position.

//tbody/tr/td[count(//tbody/tr/th[contains(., "Brand Name")]/preceding-sibling::th) + 1]

Testing the xpath with lxml in iPython:

In [47]: root.xpath('//tbody/tr/td[count(//tbody/tr/th[contains(., "Brand Name")]/preceding-sibling::th) + 1]')
Out[47]: 
[<Element td at 0x7f887c48b700>,
 <Element td at 0x7f887c89ef80>,
 <Element td at 0x7f887c5fe2c0>,
 <Element td at 0x7f887c50e580>]

In [48]: root.xpath('//tbody/tr/td[count(//tbody/tr/th[contains(., "Brand Name")]/preceding-sibling::th) + 1]/text()')
Out[48]: ['Apple', 'Samsung', 'LG', 'Motorolla']
Forensic_07
  • 1,125
  • 1
  • 6
  • 10