我想从下面提到的json链接的"SKU"
列表中检索所有collapseValues
值。谁能帮我吗?
链接:https://www.grainger.com/product/tableview/GRAINGER-APPROVED-Square-Head-Plugs-WP7366807&s_pp=false
我的代码:
x = requests.get(f"grainger.com/product/tableview/…"
for p in x['records']:
for child in p['children']:
for item in json.loads(child['collapseValues']):
url = f"grainger.com/product{item ['sku']}"
print(url)
但是发生了无助的KeyError: 'collapseValues'
。
答案 0 :(得分:2)
简单遍历json结果:
import requests
import json
url ="https://www.grainger.com/product/tableview/GRAINGER-APPROVED-Square-Head-Plugs-WP7366807&s_pp=false"
r = requests.get(url)
for records in r.json()["records"]:
for children in records["children"]:
if "collapseValues" in children:
values = json.loads(children["collapseValues"])
for val in values:
print(val["sku"])
输出:
1UVP9
2KVX4
2KVX5
1UVR4
2KVY3
2KVY4
1UVR2
2KVX8
2KVX9