【问题标题】:(Python 3 OS Win7) List not showing the expected output(Python 3 OS Win7)列表未显示预期输出
【发布时间】: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


【解决方案1】:

如果你想要一个列表,你必须建立一个列表。您需要先声明空列表,然后在每次迭代中附加值:

res = []
for tag in tags:
    # Look at the parts of a tag
    print('TAG:', tag)
    res.append(re.findall('[0-9]+',str(tag)))

print(res)

如果你需要一个可读性很强的输出,你可以使用pprint

import pprint
pprint.pprint(res)

(通过在最后打印num,在循环之外,您只打印最后计算的值,从循环中转义)

【讨论】: