python - 如何使用 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)
解决方案
事实上,您一直在添加同一个对象,请记住 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'] = ...
推荐阅读
- node.js - 对在 nodejs 中使用 node-windows 为 helloworld.js 编写脚本感到困惑
- xcode-ui-testing - 使用 XCUIElement 上的谓词等待焦点
- vb.net - 如何在 Vb.Net 中隐式转换枚举类型
- excel - 删除 Excel 工作表中的特定行
- ionic-framework - Ionic 3 - 如何在禁用(透明)按钮后面移动内容
- angular - Ionic 3 中的数组等可迭代对象
- javascript - 查找浏览器生成的 javascript 变量的当前值
- javascript - 在物化中动态刷新 HTML 选择
- android - 如何从谷歌地图中删除多边形
- osgi - Fuse 7 中的 KIE 功能