Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to select table column by column header name with xpath

Tags:

select

xpath

I have a table of results and it looks like following:

<table>
  <thead>
    <tr>
      <th>Id</th>
      <th>Type</th>
      <th>Amount</th>
      <th>Price</th>
      <th>Name</th>
      <th>Expiration</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>123</td>
      <td>Paper</td>
      <td>10 pcs.</td>
      <td>$10</td>
      <td>Premium Copier paper</td>
      <td>None</td>
    </tr>
    <tr>
      <td>321</td>
      <td>Paper</td>
      <td>20 pcs.</td>
      <td>$20</td>
      <td>Extra Copier paper</td>
      <td>None</td>
    </tr>
  </tbody>

And i want to select the whole column by its name with xpath e.g. i want the returned result to be an array of {<td>$10</td>, <td>$20</td>} if selected by column name "Price". I'm new to xpath and not really sure how to do this, but i'm pretty sure it's possible.

like image 462
Eduard Sukharev Avatar asked Feb 07 '13 07:02

Eduard Sukharev


People also ask

How do I find the XPath of a column in a table?

Let's select an element in the web table and find its XPath. For Chrome, right-click and inspect the given element to find its XPath. To find the XPath of a UI element in Firefox, right-click on the desired element, go to “Inspect Element” to open the inspector which will help identify its XPath.

Which method should be used to retrieve the table header?

We shall use the locator xpath and then use find_elements_by_xpath method. The list of headers will be returned.


1 Answers

Ok, i've found the answer that would suffice and look quite elegant. Here goes the required XPath string:

//table/tbody/tr/td[count(//table/thead/tr/th[.="$columnName"]/preceding-sibling::th)+1]

Put a name of the column instead of $columnName. This works well for me. There's no XSL or anything, just pure xpath string. How to apply it - it's another question.

like image 195
Eduard Sukharev Avatar answered Sep 18 '22 09:09

Eduard Sukharev