繁体   English   中英

如何仅从 HTML 代码中打印和求和数字?(Python)

[英]How to print and sum only numbers from HTML code?(Python)

问题是我无法从 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM