python - 如何仅打印 HTML 代码中的数字并对其求和?(Python)

标签 python html numbers

问题是我无法从 HTML 代码中获取数字。

最佳答案

import re
from bs4 import BeautifulSoup

url = str(input())
soup = BeautifulSoup(url,"html.parser")
data = soup.find_all('td')
numbers = [d.text for d in data if d.text.isdigit()] # if the text of the td element is a number, include it in the list assigned to the variable 'numbers'
print(numbers)
>>> ['23', '40']

本质上,将其分解为更小的步骤:

  • 分离出可能包含您要查找的数据的所有 HTML 元素(在本例中为 <td> 元素)

  • 对于每个元素,使用 str.isnumber() 方法检查它是否包含数字:str.isdigit() doc

关于python - 如何仅打印 HTML 代码中的数字并对其求和?(Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55385655/

相关文章:

python - 在 python 中只保留 int

algorithm - 数字形成

python - 为什么调用 .clear() 后字典大小为 72 字节,而实例化时为 240 字节?

python - 是否可以在 Sublime Text 3 输出面板中显示图像?

javascript - 使用本地存储创建并保存帐户

c# - 使用 C# 正则表达式去除 HTML 标签

javascript - 当我尝试通过 Id 获取标签时,为什么我的 jQuery 不工作?

python - 迭代 Flask 中提交的表单字段?

python - 当我从数据框中的一行中创建一个列表时,它在 for 循环中仅迭代一次,而当对列执行相同操作时,它工作得很好

c - 埃拉托斯特尼筛法,素数 C