python xpath loop through paragraphs and grab <strong>
<p>I have a series of paragraphs I'm trying to parse using xpath. The html is formatted like this:</p>

<pre><code>&lt;div id="content_third"&gt;
 &lt;h3&gt;Title1&lt;/h3&gt;
 &lt;p&gt;
  &lt;strong&gt;District&lt;/strong&gt;
  John Q Public &lt;br&gt;
  Susie B Private 
 &lt;p&gt;
 &lt;p&gt;
  &lt;strong&gt;District&lt;/strong&gt;
  Anna C Public &lt;br&gt;
  Bob J Private 
 &lt;p&gt;
 &lt;h3&gt;Title1&lt;/h3&gt;
 &lt;p&gt;
  &lt;strong&gt;District&lt;/strong&gt;
  John Q Public &lt;br&gt;
  Susie B Private 
 &lt;p&gt;
 &lt;p&gt;
  &lt;strong&gt;District&lt;/strong&gt;
  Anna C Public &lt;br&gt;
  Bob J Private 
 &lt;p&gt;
&lt;/div&gt;
</code></pre>

<p>I'm setting up an initial loop like this:</p>

<pre><code>titles = tree.xpath('//*[@id="content_third"]/h3')
for num in range(len(titles):
</code></pre>

<p>Then an inner loop:</p>

<pre><code>district_races = tree.xpath('//*[@id="content_third"]/p[count(preceding-sibling::h3)={0}]'.format(num))
for index in range(len(district_races)):
</code></pre>

<p>Each loop, I want to select just the "District" within that <code>strong</code>. I've tried this, which spits out empty arrays except for one that's filled with all the Districts:</p>

<pre><code>zone = tree.xpath('//*[@id="content_third"]/p[count(preceding-sibling::h3)={0}/strong[{1}]/text()'.format(num, index))
</code></pre>

<p>Gotta love those unformatted state election webpages.</p>

<p>I presume  each <em>District</em> is a placeholder for some actual name so to get  each District is a lot simpler than what you are trying to do, just extract the <em>text</em> from each <em>strong</em> inside each <em>p</em>:</p>

<pre><code>h = """&lt;div id="content_third"&gt;
 &lt;h3&gt;Title1&lt;/h3&gt;
 &lt;p&gt;
  &lt;strong&gt;District&lt;/strong&gt;
  John Q Public &lt;br&gt;
  Susie B Private
 &lt;p&gt;
 &lt;p&gt;
  &lt;strong&gt;District&lt;/strong&gt;
  Anna C Public &lt;br&gt;
  Bob J Private
 &lt;p&gt;
 &lt;h3&gt;Title1&lt;/h3&gt;
 &lt;p&gt;
  &lt;strong&gt;District&lt;/strong&gt;
  John Q Public &lt;br&gt;
  Susie B Private
 &lt;p&gt;
 &lt;p&gt;
  &lt;strong&gt;District&lt;/strong&gt;
  Anna C Public &lt;br&gt;
  Bob J Private
 &lt;p&gt;
&lt;/div&gt;"""

from lxml import html

tree = html.fromstring(h)

print(tree.xpath('//*[@id="content_third"]/p/strong/text()'))
</code></pre>

python loops xpath