首页 > 解决方案 > Python网络抓取嵌套字典键对 - AttributeError

问题描述

我正在尝试从下面的 API 中获取 PGA 统计信息。

url = 'https://statdata.pgatour.com/r/stats/current/02671.json?userTrackingId=exp=1594257225~acl=*~hmac=464d3dfcda2b2ccb384b77ac7241436f25b7284fb2eb0383184f48cbdff33cc4'
response = requests.get(url)
pga_stats = response.json()

我只想选择此图像中标识的嵌套键。我已经能够使用以下代码遍历“年份”键,但除此之外,我收到以下 AttributeError。

 test = pga_stats.get('tours')[0].get('years')
        (prints reduced dictionary)

 test = pga_stats.get('tours')[0].get('years').get('stats')
       'list' object has no attribute 'get'

我的最终目标是将此玩家数据写入 csv 文件。任何建议将不胜感激。

标签: pythonlistdictionaryweb-scrapingnested

解决方案


pga_stats.get('tours')[0].get('years')返回一个列表,而不是一个字典。您实际上想get在它的第一个元素上使用该方法,如下所示:

test = pga_stats.get('tours')[0].get('years')[0].get('stats')

推荐阅读