In BeautifulSoup, Ignore Children Elements While Getting Parent Element Data
<p>I have html as follows:</p>

<pre><code>&lt;html&gt;
    &lt;div class="maindiv"&gt;
        text data here 
        &lt;br&gt;
        continued text data
        &lt;br&gt;
        &lt;div class="somename"&gt;
            text &amp; data I want to omit
        &lt;/div&gt;
    &lt;/div&gt;
&lt;/html&gt;
</code></pre>

<p>I am trying to get only the the text found in the <code>maindiv</code>element, without getting text data found in the <code>somename</code> element. In most cases, in my experience anyway, most text data is contained within some child element. I have ran into this particular case however where the data seems to be contained somewhat <em>will-nilly</em> and is a bit harder to filter.</p>

<p>My approach is as follows:</p>

<p><code>textdata= soup.find('div', class_='maindiv').get_text()</code></p>

<p>This gets all the text data found within the <code>maindiv</code> element, as well as the text data found in the <code>somename</code> div element.</p>

<p>The logic I'd like to use is more along the lines of:
<code>textdata = soup.find('div', class_='maindiv').get_text(recursive=False)</code> which would omit any text data found within the <code>somename</code> element.</p>

<p>I know the <code>recursive=False</code> argument works for locating only parent-level elemenets when searching the DOM structure using BeautifulSoup, but can't be used with the <code>.get_text()</code> method.</p>

<p>I've realized the approach of finding all the text, then subtracting the string data found in the <code>somename</code> element from the string data found in the <code>maindiv</code> element, but I'm looking for something a little more efficient.</p>