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

如何使用for循环将多个Python字典正确追加到列表中

问题原因
  • 你把prop_info字典的初始化放在了for循环的外层,整个遍历过程中操作的都是同一个字典对象,Python里字典是可变类型,列表append的时候存的是字典的内存引用而非当时的副本,所以每次修改prop_info都会覆盖之前的内容,最终列表里所有元素都指向最后一次修改后的字典。
  • 额外隐含问题:函数参数是url,但代码里请求用的是大写的URL全局变量,参数没有生效,且空的except语句会吞掉所有报错,不利于后续调试定位问题。
修正方案

把prop_info = {}这行代码移到for循环内部,每次遍历新的房产条目时都创建一个全新的字典对象,再赋值存入列表即可。

修正后完整代码
import requests as r
from bs4 import BeautifulSoup as bs

def get_property_details(url):
    page = r.get(url) # 改用传入的参数url,避免依赖全局变量
    soup = bs(page.content, 'html.parser')
    div = soup.find_all('div', class_ = 'list-card-heading uk-grid')
    
    property_list = []
    try:
        for d in div:
            # 每次循环新建空字典,为核心修改点
            prop_info = {}
            details = d.find_all('li')
            prop_info['Price'] = d.find('b', class_ = 'list-price').get_text().strip().replace('$','').replace('/mo','').replace('\xa0','')
            prop_info['Type'] = d.find('span', class_ = 'rent_type').get_text().strip()
            
            for index, detail in enumerate(details):
                if index == 0:
                    prop_info['Bed'] = detail.text.strip().replace(' bds','')   
                elif index == 1:
                    prop_info['Bath'] = detail.text.strip().replace(' ba','')          
                elif index == 2:
                    prop_info['SQFT'] = detail.text.strip().replace(' sqft','')             
                else:
                    break
            print(prop_info)
            property_list.append(prop_info)
                        
    except Exception as e:
        # 输出报错信息方便调试
        print(f"解析出错:{e}")
        
    return property_list

URL = 'https://www.forrentbyowner.com/?showpage=/classifieds/&f=Oklahoma'
property_info = get_property_details(URL)
print(property_info)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 19:06:03