【问题标题】:How to find sum of a for loop in BeautifulSoup如何在 BeautifulSoup 中找到 for 循环的总和
【发布时间】:2019-10-27 18:27:51
【问题描述】:

请在此处查看我的代码: 示例网址: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)

【问题讨论】:

    标签: python beautifulsoup


    【解决方案1】:

    一些提示,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)
    

    此外,您可以检查this question 以了解+==+ 之间的区别

    【讨论】:

    • 是的,我得到了答案,但它就像这样 2418 2439 2458 2476 2494 2508 2520 2532 2541 2548 2551 2553 我想要的不仅仅是单笔总和 2553。
    • 因为在您的代码中,您的 print 语句位于 for 循环中,因此每次将任何内容添加到总数时都会打印。您应该从 for 循环中删除 print 语句,并且只在 for 循环之后打印总数
    • 知道了。谢谢,
    【解决方案2】:

    你只是有你的增量语法错误:

    sum =+ ChangeToInt
    

    应该是:

    sum += ChangeToInt
    

    在我修复它之后,你的代码对我来说工作得很好。

    【讨论】:

    • 是的,我得到了答案,但它就像这样 2418 2439 2458 2476 2494 2508 2520 2532 2541 2548 2551 2553 我想要的不仅仅是单笔总和 2553。
    猜你喜欢
    • 1970-01-01
    • 2021-02-09
    • 2023-01-25
    • 2015-12-22
    • 2020-07-27
    • 1970-01-01
    • 2021-10-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多