【发布时间】:2026-01-09 18:55:01
【问题描述】:
输入网址http://py4e-data.dr-chuck.net/comments_42.html
当我运行此代码时,预期的输出是一个列表,其中包含正在程序中解析的 tag 内的数字。但我得到的只是列表中的最后一个数字。
请更正程序以显示所有已解析标签中存在的数字列表
from urllib.request import urlopen
from bs4 import BeautifulSoup
import ssl
import re
# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
url = input('Enter - ')
html = urlopen(url, context=ctx).read()
# html.parser is the HTML parser included in the standard Python 3 library.
# information on other HTML parsers is here:
# http://www.crummy.com/software/BeautifulSoup/bs4/doc/#installing-a-parser
soup = BeautifulSoup(html, "html.parser")
# Retrieve all of the anchor tags
sum_of_num = 0
tags = soup('tr')
for tag in tags:
# Look at the parts of a tag
print('TAG:', tag)
num = re.findall('[0-9]+',str(tag))
print(num)
【问题讨论】:
-
可以通过 span.cmets 进行选择,即:
soup.select('span.comments')。然后获取文本,转为 int 并求和。
标签: python list beautifulsoup html-parsing