Using xpath to loop over all <h2> tags within a speciifc div
<p>I am trying to loop over every <code>&lt;h2&gt;</code> tag (get the text of it) that is inside div's with the <code>id="somediv"</code> using this code:</p>

<pre><code>for k,div1 in enumerate(tree.xpath('//div[@id="someid"]')):
  print div1.xpath('.//h2['+str(k+1)+']/text()')
</code></pre>

<p>but it doesn't work. Why? However this works:</p>

<pre><code>for i in range(5): #let's say there are 5 div's with id="someid" to make things easier
  print tree.xpath('//div[@id="someid"]/div/div[1]/div[2]/h2['+str(i)+']/text()'))
</code></pre>

<p>Problem here is, that I have to give the absolute path <code>.../div/div[1]/div[2]...</code> which I don't want. My first solution looks nice but is not producing the desired result, instead I can only retrieve all <code>&lt;h2&gt;</code> tags from one <code>div="someid"</code> at a time. Can anyone tell me what I am doing wrong?</p>

<p><code>.//</code> will continue the search down the tree. A list of h2 text nodes subordinate to your div is just</p>

<pre><code>tree.xpath('//div[@id="someid"]/.//h2/text()'))
</code></pre>

python xpath