Xpath selecting th element based on td element's position
<p>Good afternoon, today I got an HTML document to parse.</p>

<pre><code>&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;body&gt;

&lt;table name="test" style="width:100%"&gt;
  &lt;tr&gt;
    &lt;th&gt;First name&lt;/th&gt;
    &lt;th&gt;Last name&lt;/th&gt;
    &lt;th&gt;Age&lt;/th&gt;
  &lt;/tr&gt;
  &lt;tr&gt;
    &lt;td&gt;Jill&lt;/td&gt;
    &lt;td&gt;Smith&lt;/td&gt;
    &lt;td&gt;50&lt;/td&gt;
  &lt;/tr&gt;
  &lt;tr&gt;
    &lt;td&gt;Eve&lt;/td&gt;
    &lt;td&gt;Jackson&lt;/td&gt;
    &lt;td&gt;94&lt;/td&gt;
  &lt;/tr&gt;
  &lt;tr&gt;
    &lt;td&gt;John&lt;/td&gt;
    &lt;td&gt;Doe&lt;/td&gt;
    &lt;td&gt;80&lt;/td&gt;
  &lt;/tr&gt;
&lt;/table&gt;

&lt;/body&gt;
&lt;/html&gt;
</code></pre>

<p>Basically, it's a very simple table. I know how to parse such document with python and lxml, and I also managed to retrieve most of the informations I need in that kind of document.</p>

<p>Nonetheless, I have some troubles to get the text value of a th element which has the same <code>position()</code> as a td element. </p>

<p><em>What I've done so far :</em></p>

<p>With one xpath like that one I retrieve all of my td elements :</p>

<pre><code>/html/body/table[@name='test']/tr/td
</code></pre>

<p>I then apply another xpath to each element to get the right th element.</p>

<p>I'm using something like that :</p>

<pre><code>./ancestor::table/tr/th[position()=count(./preceding-sibling::td)+1]
</code></pre>

<p>Nonetheless, this is not working, my count function returns 0. I guess the path I'm giving (./preceding-sibling::td) is refering to th/preceding-sibling::td. Thus, with no td element existing in the same row as th, the count function returns 0. I'd like to refer to the td element I'm querying instead. </p>

<p>Yet I don't know how to do that, and the only good answer I found on that subject (<a href="https://stackoverflow.com/questions/18960462/xpath-find-table-cell-with-same-position-in-different-row">xpath: find table cell with same position in different row</a>) is based on the fact the user knows an identifier for the td to find. I just can't hardcode a td text value in my xpath.</p>

<p>Is there any way to do that with xpath only ?</p>

<p>Thanks for any help you can provide.</p>

<p>EDIT :</p>

<p><a href="https://stackoverflow.com/questions/1022345/current-node-vs-context-node-in-xslt-xpath">Current node vs. Context node in XSLT/XPath?</a></p>

<p>According to that answer, my xpath is selecting the context node, which in my case is the <strong>th</strong> element. What I need is to select the current node, which is a <strong>td</strong> element to which I'm applying that piece of code :</p>

<pre><code>lxmlelement.xpath('./ancestor::table/tr/th[position()=count(./preceding-sibling::td)+1]')
</code></pre>