如何提取Python嵌套字典中的动态键以对比商品最低变体价格
解决方案
实现思路
- 不需要硬编码
attributes下的动态键名,直接通过dict.values()获取attributes下的所有属性对象,所有属性的结构统一,都包含options字段存储商品变体信息 - 遍历所有
options提取商品ID、规格名称,关联对应optionPrices和pricePerServingsMap中的价格数据 - 整理所有变体的价格信息后,按每份单价排序即可找到成本最低的变体
完整可运行代码
import requests import json from bs4 import BeautifulSoup url = 'https://www.bulk.com/uk/b-vitamin-complex-tablets.html' r = requests.get(url) soup = BeautifulSoup(r.content,'html.parser') # 提取JSON数据 script = soup.find_all('script')[55].string.strip()[449:-80] data = json.loads(script) # 存储所有商品变体信息 variant_list = [] # 遍历attributes下所有动态键对应的属性值,不需要提前知道键名 for attr in data['attributes'].values(): # 遍历当前属性下的所有规格选项 for option in attr['options']: # 提取商品ID,每个option对应唯一商品ID product_id = option['products'][0] # 提取对应价格信息 final_price = data['optionPrices'][product_id]['finalPrice']['amount'] price_per_serving = data['pricePerServingsMap'][product_id]['price_per_serving'] servings = data['pricePerServingsMap'][product_id]['servings'] # 存入列表 variant_list.append({ 'product_id': product_id, 'spec': option['label'], 'final_price': final_price, 'servings': servings, 'price_per_serving': price_per_serving }) # 按每份单价升序排序,第一个就是最低成本的变体 variant_list.sort(key=lambda x: x['price_per_serving']) cheapest_variant = variant_list[0] # 输出结果 print("最低成本商品变体信息:") print(f"商品ID:{cheapest_variant['product_id']}") print(f"规格:{cheapest_variant['spec']}") print(f"最终售价:£{cheapest_variant['final_price']}") print(f"总份数:{cheapest_variant['servings']}") print(f"每份单价:£{cheapest_variant['price_per_serving']}")
逻辑说明
- 用
data['attributes'].values()直接跳过动态键名获取属性内容,适配不同商品的属性ID变化 - 所有变体信息统一整理后排序,不需要提前知道商品ID的取值范围,自动适配所有在售变体
- 如果需要按最终售价排序,只需把排序的key改为
lambda x: x['final_price']即可
内容的提问来源于stack exchange,提问作者MarkWP
相关产品推荐
相关产品推荐

