首页 > 解决方案 > 如何在 BeautifulSoup 中找到 for 循环的总和

问题描述

请在此处检查我的代码:示例 url:http ://py4e-data.dr-chuck.net/comments_42.html 在以下 url 中找到的数字总和应为 (2553)。我必须尝试使用​​几种技术进行总结,但使用代码顶部提供的 url 找不到正确的技术。我需要总结字符串数字。

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

# To read the file from the url
url = input('Enter - ')
html = urllib.request.urlopen(url, context=ctx).read()
soup = BeautifulSoup(html, "html.parser")

# To search for specific area of the file
tags = soup('span')
#print(tags)
sum = 0

# Filters your search further and prints the specific part as                     
#string
for tag in tags:
    print(tag.contents[0])
    #ChangeToInt = int(tag.contents[0])
    #sum =+ ChangeToInt
    #print(sum)

标签: pythonbeautifulsoup

解决方案


一些指针,sum是一种用于汇总数字列表的python内置方法,因此最好不要将其用作变量名。添加到变量的语法也是,+=但在你的代码中你有=+. 您的代码只需更改该语法即可工作(我还将变量名称从 sum 更新为 total 并在循环后仅打印总数。

total = 0
for tag in tags:
    print(tag.contents[0])
    ChangeToInt = int(tag.contents[0])
    total += ChangeToInt
print(total)

或者,您可以使用 python 的 sum 方法和列表推导来生成数字。

total = sum([int(tag.contents[0]) for tag in tags])
print(total)

另外,您可以检查此问题+=以了解和之间的区别=+


推荐阅读