【问题标题】:Scrape specific value from a json从 json 中抓取特定值
【发布时间】:2021-11-13 16:45:35
【问题描述】:

我想从这个例子中抓取一些东西,我的目标是通过匹配 json 文件(例如 5.5/6)内部的 title 来抓取一些值并专注于它们,我想让我的脚本只为具有 titleoption1/2/3 数字 6

的部分选择值
({
    "id": 39430269435981,
    "title": "5.5",
    "option1": "5.5",
    "option2": null,
    "option3": null,
    "sku": "195241242248",
    "requires_shipping": true,
    "taxable": true,
    "featured_image": null,
    "available": false,
    "name": "Nike Dunk High 1985 - Lemon Drop / Black / Saturn Gold - 5.5",
    "public_title": "5.5",
    "options": ["5.5"],
    "price": 13108,
    "weight": 1361,
    "compare_at_price": null,
    "inventory_management": "shopify",
    "barcode": null
},
{
    "id": 39430269468749,
    "title": "6",
    "option1": "6",
    "option2": null,
    "option3": null,
    "sku": "195241242255",
    "requires_shipping": true,
    "taxable": true,
    "featured_image": null,
    "available": false,
    "name": "Nike Dunk High 1985 - Lemon Drop / Black / Saturn Gold - 6",
    "public_title": "6",
    "options": ["6"],
    "price": 13108,
    "weight": 1361,
    "compare_at_price": null,
    "inventory_management": "shopify",
    "barcode": null
}

我该怎么做?如何只抓取标题为 6 的部分的 id

【问题讨论】:

  • beautifulsoup 被标记在这里有什么原因吗?我认为这只是一个 JSON 问题?

标签: python json web-scraping beautifulsoup


【解决方案1】:

在您的情况下必须有一个更具体的方法,但通用方法是将这个“json”转换为一个字典列表并遍历它们,例如:

import json

jstring = '''
[
{
    "id": 39430269435981,
    "title": "5.5",
    "option1": "5.5",
    "option2": null,
    "option3": null,
    "sku": "195241242248",
    "requires_shipping": true,
    "taxable": true,
    "featured_image": null,
    "available": false,
    "name": "Nike Dunk High 1985 - Lemon Drop / Black / Saturn Gold - 5.5",
    "public_title": "5.5",
    "options": ["5.5"],
    "price": 13108,
    "weight": 1361,
    "compare_at_price": null,
    "inventory_management": "shopify",
    "barcode": null
},
{
    "id": 39430269468749,
    "title": "6",
    "option1": "6",
    "option2": null,
    "option3": null,
    "sku": "195241242255",
    "requires_shipping": true,
    "taxable": true,
    "featured_image": null,
    "available": false,
    "name": "Nike Dunk High 1985 - Lemon Drop / Black / Saturn Gold - 6",
    "public_title": "6",
    "options": ["6"],
    "price": 13108,
    "weight": 1361,
    "compare_at_price": null,
    "inventory_management": "shopify",
    "barcode": null
}
]
'''
jlist = json.loads(jstring)

for jdict in jlist:
    if ( jdict['title'] == "6" ):
        print(jdict['id'])

输出

39430269468749

【讨论】:

    猜你喜欢
    • 2021-09-27
    • 2021-09-05
    • 2022-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-08
    • 2019-03-30
    • 2021-12-30
    相关资源
    最近更新 更多