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

网页数据提取:列表仅保留首个循环生成的字典项问题

问题解决:循环仅生成单个字典的问题

你的核心问题是**list.append(dictionary)的缩进错误**,这条语句被放在了for循环的外面,导致循环结束后才会执行一次append操作,最终列表里只会保留最后一次循环生成的字典(你看到仅输出首个结果,大概率是后续迭代中提取数据时出错,导致字典未被正确生成,但首要问题是缩进错误)。

修正后的代码

# 不要用list作为变量名,避免覆盖Python内置类型
property_list = []
for item in data:
    dictionary = {}
    dictionary['Address'] = item.find('div',{'class':'property-address'}).text.replace(' ','').strip()    
    dictionary['Locality'] = item.find('div',{'class':'property-city'}).text.replace(' ','').strip()
    dictionary['Beds'] = item.find('div',{'class':'property-beds'}).find('strong').text
    try:
        dictionary['Baths'] = item.find('div',{'class':'property-baths'}).find('strong').text
    except:
        pass  
    try: 
        dictionary['Square Feet'] = item.find('div',{'class':'property-sqft'}).find('strong').text
    except:
        pass     
    dictionary['Price'] = item.find('a',{'class':'listing-price'}).text.replace('\n','').replace(' ','')
    # 将append语句缩进,放到循环内部
    property_list.append(dictionary)

说明

调整缩进后,每次循环生成一个新的房产信息字典,就会立刻添加到列表中,循环结束后列表就会包含所有迭代生成的字典。另外建议不要用list作为变量名,它是Python的内置类型,用这个名字会覆盖内置函数,容易引发其他隐性问题。

内容的提问来源于stack exchange,提问作者project work

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 16:30:26