span tags- how do I sum the numbers on HTML with span tag

Viewed 168

I have a URL and am trying to sum the numbers on it, through span tags. Can anyone help to amend the code below to do such a thing?: (the URL is: http://py4e-data.dr-chuck.net/comments_1050359.html)

from urllib.request import urlopen
from bs4 import BeautifulSoup
import ssl

# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

url = input('Enter - ')
html = urlopen(url, context=ctx).read()
soup = BeautifulSoup(html, "html.parser")

# Retrieve all of the anchor tags
tags = soup('a')
for tag in tags:
    # Look at the parts of a tag
    print('TAG:', tag)
    print('URL:', tag.get('href', None))
    print('Contents:', tag.contents[0])
    print('Attrs:', tag.attrs)
1 Answers

To sum all the numbers, you can try this:

tags = soup.find_all('span', class_ = 'comments')
total = sum([int(tag.text) for tag in tags])

Full code:

from urllib.request import urlopen
from bs4 import BeautifulSoup
import ssl

# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

url = 'http://py4e-data.dr-chuck.net/comments_1050359.html'
html = urlopen(url, context=ctx).read()
soup = BeautifulSoup(html, "html.parser")

tags = soup.find_all('span', class_ = 'comments')
total = sum([int(tag.text) for tag in tags])

print(total)

Output:

2692
Related