【发布时间】:2019-04-29 19:16:54
【问题描述】:
我正在对两个 json 文件进行网络抓取数据。
第一个有一些我可以收集的数据。
第二个没有所需的数据。而我想存储“NA”。
我的问题是我不知道如何在脚本中正确存储“NA”。
这是我的代码:
import requests
# this is our profile ids
profile=['kaid_896965538702696832878421','kaid_1143236333220233567674383']
# prepare the list to get data
badgechall=[]
# do this for each profile id
for kaid in profile:
# request the api link of the profile
data = requests.get('https://www.khanacademy.org/api/internal/user/{}/profile/widgets?lang=en&_=190424-1429-bcf153233dc9_1556201931959'.format(kaid)).json()
# go through each json file to get the data
for item in data:
# try to find on each dictionary of the list the desired data or pass
try:
for badges in item['renderData']['badgeCountData']['counts']:
if badges['typeLabel'] == 'Challenge Patches':
badgechall.append(badges['count'])
except KeyError:
pass
print(badgechall)
当我运行这段代码时,我得到:
[100]
我想得到的是:
[100, 'NA']
'100'对应第一个配置文件'kaid_896965538702696832878421'和'NA'对应第二个配置文件'kaid_1143236333220233567674383'。
我想要第一个和第二个链接的数据,如果没有返回'NA'。所以我们应该有一个只有 2 个值的列表。
我试过了:
except KeyError:
badgechall.append('NA')
pass
但它返回:
[100, 'NA', 'NA', 'NA', 'NA', 'NA', 'NA', 'NA']
【问题讨论】:
-
我对你想要做什么感到困惑,你能澄清一下吗?
-
也许您希望在
for循环中包含try/except,而不是在try/except块中包含for循环? -
@BenI 我试图澄清。好点了吗?
标签: python json python-3.x web-scraping