You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将BeautifulSoup4(BS4)爬取结果完整存入变量供后续使用

问题原因
  • 你在for循环内每次匹配到符合要求的title属性时,都直接对fixtures变量做赋值操作,新的值会直接覆盖上一轮循环存入的内容,因此循环结束后变量里只会保留最后一次循环的结果,无法存储全部匹配内容。
修复方案

提前初始化一个空列表用来存储所有匹配到的赛程数据,循环过程中把符合要求的内容追加到列表中即可,修改后的代码如下:

import requests
from bs4 import BeautifulSoup as bs

url= "https://www.bbc.com/sport/football/scores-fixtures/"
date = input("Input the date, hit Enter for today")
src = url + date

html = requests.get(src).text
soup = bs(html, 'lxml')

select = soup.find_all('abbr')
# 初始化空列表存储所有结果
fixtures = []
for abbr in select:
    if abbr.has_attr('title'):
        fixtures.append(str(abbr['title']))

# 循环外打印全部结果
print('\n'.join(fixtures))
补充说明
  • 后续需要和Excel比对数据时,直接遍历fixtures列表即可拿到所有爬取到的赛程title内容。
  • 原代码中input(str("Input the date, hit Enter for today"))写法冗余,input参数本身要求传入字符串,无需额外套str()转换。

内容的提问来源于stack exchange,提问作者Aymen Eddaoudi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 10:06:04