【问题标题】:Assistance with extracting URL from Pocket reading list using Python dictionary协助使用 Python 字典从袖珍阅读列表中提取 URL
【发布时间】:2016-04-15 07:19:23
【问题描述】:

鉴于此 http 响应(Python 字典)

{"status":1,"list":{"229279689":{"item_id":"229279689",
"resolved_id":"229279689",
"given_url":"http:\/\/www.grantland.com\/blog\/the-triangle\/post\/_\/id\/38347\/ryder-cup-preview",
"given_title":"The Massive Ryder Cup Preview - The Triangle Blog - Grantland",
"favorite":"0",
"status":"0",
"resolved_title":"The Massive Ryder Cup Preview",
"resolved_url":"http:\/\/www.grantland.com\/blog\/the-triangle\/post\/_\/id\/38347\/ryder-cup-preview",
"excerpt":"The list of things I love about the Ryder Cup is so long that it could fill a (tedious) novel, and golf fans can probably guess most of them.",
"is_article":"1",
"has_video":"1",
"has_image":"1",
"word_count":"3197",
"images":{"1":{"item_id":"229279689","image_id":"1",
    "src":"http:\/\/a.espncdn.com\/combiner\/i?img=\/photo\/2012\/0927\/grant_g_ryder_cr_640.jpg&w=640&h=360",
    "width":"0","height":"0","credit":"Jamie Squire\/Getty Images","caption":""}},
"videos":{"1":{"item_id":"229279689","video_id":"1",
    "src":"http:\/\/www.youtube.com\/v\/Er34PbFkVGk?version=3&hl=en_US&rel=0",
    "width":"420","height":"315","type":"1","vid":"Er34PbFkVGk"}}}}}

如何在事先不知道“item_id”的情况下提取“given_url”? (两者都是位于响应顶部的键)。

【问题讨论】:

    标签: python json url extract pocket


    【解决方案1】:

    如果list下有很多项目,您可以使用以下代码提取所有url:

    urls = [x['given_url'] for x in d['list'].itervalues() if 'given_url' in x]
    print urls # ['http:\\/\\/www.grantland.com\\/blog\\/thetriangle\\/post\\/_\\/id\\/38347\\/ryder-cup-preview']
    

    【讨论】:

    • 感谢您的输入,效果很好。我想知道您是否知道将 x['given_url'] 放在开头以及将迭代器和条件放在代码行末尾的格式名称?
    • 格式名称是什么意思? item_id 还是别的什么?
    【解决方案2】:

    试试下面这行代码:

    try:
        print data['list'].values()[0]['given_url']
    except IndexError:
        print "No data"
    
    #output:
    http:\\/\\/www.grantland.com\\/blog\\/the-triangle\\/post\\/_\\/id\\/38347\\/ryder-cup-preview
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-02
      • 1970-01-01
      • 2010-10-29
      • 2022-11-28
      • 2015-12-24
      • 1970-01-01
      • 2021-09-21
      相关资源
      最近更新 更多