使用BeautifulSoup计算img标签

时间:2017-04-25 03:24:34

标签: python-3.x beautifulsoup

我想计算dark_circle.svg的数量并打印该数字。我如何完成这项任务?

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())

输出:

<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>

1 个答案:

答案 0 :(得分:2)

您可以迭代img代码并计算其实例:

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

一个班轮:

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