如何使用请求从json获取值?

时间:2018-12-14 07:11:25

标签: python json web-scraping

我想从下面提到的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'

1 个答案:

答案 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