Life is complex
Life is complex

Reputation: 15619

Using BeautifulSoup to count img tags

I would like to count the number of dark_circle.svg and print that number. How do I accomplish this task?

CODE:

sidebar_details = SoupParser.find('div', {'class': 'sidebar-content'})
// additional working code removed
for sidebar_rows in sidebar_details.find_all("td")[::2]:
    if "Risk" in sidebar_rows:
        print (sidebar_rows.findNextSiblings())

OUTPUT:

<td> <span><img src="/images/ratings/dark_circle.svg" width="15"/></span>
<span><img src="/images/ratings/dark_circle.svg" width="15"/></span>
<span><img src="/images/ratings/dark_circle.svg" width="15"/></span>
<span><img src="/images/ratings/dark_circle.svg" width="15"/></span>
<span><img src="/images/ratings/light_circle.svg" width="15"/></span>
</td>

Upvotes: 1

Views: 1432

Answers (1)

akash karothiya
akash karothiya

Reputation: 5950

You can iterate img tag and count its instance :

darkcircle = 0
for i in soup.select('img'):
    if 'dark_circle' in i['src']:
        darkcircle += 1
>>> print(darkcircle)
4

One liner :

>>> sum([ 1 for i in soup.find_all('img') if 'dark_circle' in i['src']])
4

Upvotes: 2

Related Questions