Python - Beautifulsoup count only outer tag children of a tag
<p>HTML of page:</p>

<pre><code>&lt;form name="compareprd" action=""&gt;
    &lt;div class="gridBox product " id="quickLookItem-1"&gt;
        &lt;div class="gridItemTop"&gt;
        &lt;/div&gt;
    &lt;/div&gt;
    &lt;div class="gridBox product " id="quickLookItem-2"&gt;
        &lt;div class="gridItemTop"&gt;
        &lt;/div&gt;
    &lt;/div&gt;
    &lt;!-- many more like this. --&gt;
</code></pre>

<p>
I am using Beautiful soup to scrap a page. In that page I am able to get a form tag by its name.</p>

<pre><code>tag = soup.find("form", {"name": "compareprd"})
</code></pre>

<p>Now I want to count all immediate child divs but not all nested divs.
Say for example there are 20 immediate divs inside form.
I tried :</p>

<pre><code>len(tag.findChildren("div"))
</code></pre>

<p>But It gives 1500.</p>

<p>I think it gives all "div" inside "form" tag.</p>

<p>Any help appreciated.</p>

<p>You can use a single  <em>css selector</em> <code>form[name=compareprd] &gt; div</code> which will find <em>div's</em> that are immediate children of the form:</p>

<pre><code>html  = """&lt;form name="compareprd" action=""&gt;
&lt;div class="gridBox product " id="quickLookItem-1"&gt;
    &lt;div class="gridItemTop"&gt;
    &lt;/div&gt;
&lt;/div&gt;

&lt;div class="gridBox product " id="quickLookItem-2"&gt;
    &lt;div class="gridItemTop"&gt;
    &lt;/div&gt;
&lt;/div&gt;
&lt;/form&gt;"""

from bs4 import BeautifulSoup

soup = BeautifulSoup(html)


print(len(soup.select("form[name=compareprd] &gt; div")))
</code></pre>

<p>Or as commented pass <em>recursive=True</em> but use  <em>find_all</em>, <a href="https://github.com/JinnLynn/beautifulsoup/blob/master/bs4/element.py#L1178" rel="nofollow">findChildren</a> goes back to the bs2 days and is only provided for backwards compatability.</p>

<pre><code>  len(tag.find_all("div", recursive=False)
</code></pre>

python html web-scraping beautifulsoup