Call text but totally exclude tables
<p>I am using Beautiful Soup to load an XMl. All I need is the text, ignoring the  tags, and the <code>text</code> attribute words nice.</p>

<p>However, I would like to totally exclude anything within  <code>&lt;table&gt;&lt;\table&gt;</code> tags. I had the idea of substituting everything in between with a regex, but I am wondering whether there is a cleaner solution partly because <a href="http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454">Don't parse [X]HTML with regex!</a>. For instance:</p>

<pre><code>s =""" &lt;content&gt;&lt;p&gt;Hasselt ( ) is a &lt;link target="Belgium"&gt;Belgian&lt;/link&gt; &lt;link target="city"&gt;city&lt;/link&gt; and &lt;link target="Municipalities in Belgium"&gt;municipality&lt;/link&gt;. 
&lt;table&gt;&lt;cell&gt;Passenger growth
&lt;cell&gt;Year&lt;/cell&gt;&lt;cell&gt;Passengers&lt;/cell&gt;&lt;cell&gt;Percentage &lt;/cell&gt;&lt;/cell&gt;
&lt;cell&gt;1996&lt;/cell&gt;&lt;cell&gt;360 000&lt;/cell&gt;&lt;cell&gt;100%&lt;/cell&gt;
&lt;cell&gt;1997&lt;/cell&gt;&lt;cell&gt;1 498 088&lt;/cell&gt;&lt;cell&gt;428%&lt;/cell&gt;
&lt;/table&gt;"""
clean = Soup(s)
print clean.text
</code></pre>

<p>will give </p>

<pre><code>Hasselt ( ) is a Belgian city and municipality. 
Passenger growth
YearPassengersPercentage 
1996360 000100%
19971 498 088428%
</code></pre>

<p>whereas I only want:</p>

<pre><code>Hasselt ( ) is a Belgian city and municipality.
</code></pre>

<p>You can locate the <code>content</code> element and remove all <code>table</code> elements from it, then get the text:</p>

<pre><code>from bs4 import BeautifulSoup

s =""" &lt;content&gt;&lt;p&gt;Hasselt ( ) is a &lt;link target="Belgium"&gt;Belgian&lt;/link&gt; &lt;link target="city"&gt;city&lt;/link&gt; and &lt;link target="Municipalities in Belgium"&gt;municipality&lt;/link&gt;.
&lt;table&gt;&lt;cell&gt;Passenger growth
&lt;cell&gt;Year&lt;/cell&gt;&lt;cell&gt;Passengers&lt;/cell&gt;&lt;cell&gt;Percentage &lt;/cell&gt;&lt;/cell&gt;
&lt;cell&gt;1996&lt;/cell&gt;&lt;cell&gt;360 000&lt;/cell&gt;&lt;cell&gt;100%&lt;/cell&gt;
&lt;cell&gt;1997&lt;/cell&gt;&lt;cell&gt;1 498 088&lt;/cell&gt;&lt;cell&gt;428%&lt;/cell&gt;
&lt;/table&gt;"""
soup = BeautifulSoup(s, "xml")

content = soup.content
for table in content("table"):
    table.extract()

print(content.get_text().strip())
</code></pre>

<p>Prints:</p>

<pre><code>Hasselt ( ) is a Belgian city and municipality.
</code></pre>

python xml xml-parsing beautifulsoup