Retrieving tail text from html
<p>Python 2.7 using lxml</p>

<p>I have some annoyingly formed html that looks like this:</p>

<pre><code>&lt;td&gt;
&lt;b&gt;"John"
&lt;/b&gt;
&lt;br&gt;
"123 Main st.
"
&lt;br&gt;
"New York
"
&lt;b&gt;
"Sally"
&lt;/b&gt;
&lt;br&gt;
"101 California St.
"
&lt;br&gt;
"San Francisco
"
&lt;/td&gt;
</code></pre>

<p>So basically it's a single td with a ton of stuff in it. I'm trying to compile a list or dict of the names and their addresses.</p>

<p>So far what I've done is gotten a list of nodes with names using <code>tree.xpath('//td/b')</code>. So let's assume I'm currently on the <code>b</code> node for John. </p>

<p>I'm trying to get <code>whatever.xpath('string()')</code> for everything following the current node but preceding the next <code>b</code> node (Sally). I've tried a bunch of different xpath queries but can't seem to get this right. In particular, any time I use an <code>and</code> operator in an expression that has no <code>[]</code> brackets, it returns a bool rather than a list of all nodes meeting the conditions. Can anyone help out?</p>

<p>This should work:</p>

<pre><code>from lxml import etree

p = etree.HTMLParser()
html = open(r'./test.html','r')
data = html.read()
tree = etree.fromstring(data, p)

my_dict = {}

for b in tree.iter('b'):
    br = b.getnext().tail.replace('\n', '')
    my_dict[b.text.replace('\n', '')] = br

print my_dict
</code></pre>

<p>This code prints:</p>

<pre><code>{'"John"': '"123 Main st."', '"Sally"': '"101 California St."'}
</code></pre>

<p>(You may want to strip the quotation marks out!)</p>

<p>Rather than using xpath, you could use one of lxml's parsers in order to easily navigate the HTML.  The parser will turn the HTML document into an "etree", which you can navigate with provided methods.  The lxml module provides a method called <code>iter()</code> which allows you to pass in a tag name and receive all elements in the tree with that name.  In your case, if you use this to obtain all of the <code>&lt;b&gt;</code> elements, you can then manually navigate to the <code>&lt;br&gt;</code> element and retrieve its tail text, which contains the information you need. You can find information about this in the "Elements contain text" header of the <a href="http://lxml.de/tutorial.html" rel="nofollow">lxml.etree tutorial.</a></p>

python xpath lxml