python - 如何在 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)
解决方案
一些指针,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)
另外,您可以检查此问题+=
以了解和之间的区别=+
推荐阅读
- javascript - 无法将opencv与android webview一起使用
- javascript - 如何在没有按钮的情况下从本地存储中获取数据到文本字段
- sql - 从表 1 中选择表 2 上的 foreign_key = x 其中表 2 外键 = 表 3 上的 Y
- c# - 如何一次将数据表行写入多个文件N条记录?
- python - 不了解子类定义中此 TypeError 的原因
- pine-script - Pinescript - 自定义方法是否内联?
- sql - 在 Redshift 中将多行旋转到列
- passwords - 询问密码要求总是一个好主意吗?
- bluetooth - esp32蓝牙几秒钟后断开连接
- r - 如何从面积图中删除空白(geom_area)