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

Python爬虫列表添加字典异常:仅显示最后一条数据求助

问题原因与解决方案

原因分析

你在循环外部仅创建了一个dictionar字典对象,每次循环只是修改这个字典的键值对内容,而evenimente.append(dictionar)添加的是该字典的引用(不是新的字典副本)。列表中的所有元素实际上都指向同一个字典对象,因此最后打印列表时,所有元素都会显示字典最后一次被修改后的内容。

解决方案

有两种可行的修复方式:

方式一:每次循环创建新字典

将字典的定义移至for循环内部,这样每次迭代都会生成一个全新的字典对象,避免引用复用:

evenimente = []

url_fortuna = "https://efortuna.ro/"
response_fortuna = requests.get(url_fortuna)
soup_fortuna = BeautifulSoup(response_fortuna.text, "html.parser")

container_fortuna = soup_fortuna.find_all('tr')

for element in container_fortuna:
    # 每次循环初始化新字典
    dictionar = { 'casa':'',
                  'nume':'',
                  '1'   :'',
                  'x'   :'',
                  '2'   :''}
    dictionar['casa'] = 'fortuna'
    events = element.find_all('span',class_="market-name")
    odds = element.find_all('span',class_="odds-value")[0:3]
    if odds != []:
        for event in events:
            dictionar['nume'] = event.text
        dictionar['1'] = odds[0].text
        dictionar['x'] = odds[1].text
        dictionar['2'] = odds[2].text
        print(dictionar)
        evenimente.append(dictionar)
print(evenimente)

方式二:添加字典副本到列表

如果希望保留循环外的字典定义,可以在append时添加字典的副本,而非原字典的引用:

# 替换原代码中的append行
evenimente.append(dictionar.copy())

或者使用dict(dictionar)创建副本:

evenimente.append(dict(dictionar))

内容的提问来源于stack exchange,提问作者Florentin-Alexandru Iosif

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 19:22:44