首页 > 解决方案 > 如何使用 for 循环将多个 python 字典附加到列表中?

问题描述

def get_property_details(url):

    page = r.get(URL)
    soup = bs(page.content, 'html.parser')
    div = soup.find_all('div', class_ = 'list-card-heading uk-grid')
    
    try:
        prop_info = {}
        property_list = []
        count = 0
        for d in div:
            
            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
            # This prints out the correct property details
            print(prop_info)
            # This is not working, add the same property repeatedly 
            property_list.append(prop_info)
                        
    except Exception as e:
        print()
        
    # list of dictionary  
    return property_list

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

标签: pythonlistdictionaryweb-scrapingbeautifulsoup

解决方案


事实上,您一直在添加同一个对象,请记住 Python 使用“按对象引用调用”系统将参数传递给函数,这意味着当您传递字符串、数字或元组等参数时,它可以被视为“调用按值”参数,但可变对象可以被视为“按引用调用”参数,因此您一直在附加相同的对象引用,为避免这种情况,您只需prop_info = {}在 for 循环内移动以创建一个新的实例prop_info字典:

    ...
    try:
        property_list = []
        count = 0
        for d in div:
            prop_info = {}    
            details = d.find_all('li')
            prop_info['Price'] = ...

推荐阅读