抓取JSON响应时跳过NOT Available值



我有一堆URL要抓取。某些链接具有其他链接中不存在的值。我想知道,如果任何URL中都没有值,我该如何避免出现错误?

我试过tryexcept,但不起作用

在该链接中,您将在examInformation下看到4个值。我为5个值编写了表达式,但它给了我一个错误。如果值不存在,我希望它跳过。

这是我的代码:

try:
location_1 = schools['examInformation'][0]['cbrLocationShortName']
except:
pass
try:
location_2 = schools['examInformation'][1]['cbrLocationShortName']
except:
pass
try:
location_3 = schools['examInformation'][2]['cbrLocationShortName']
except:
pass
try:
location_4 = schools['examInformation'][3]['cbrLocationShortName']
except:
pass
try:
location_5 = schools['examInformation'][4]['cbrLocationShortName']
except:
pass
yield {
"Location 1": location_1 if location_1 else "N/A",
"Location 2": location_2 if location_2 else "N/A",
"Location 3": location_3 if location_3 else "N/A",
"Location 4": location_4 if location_4 else "N/A",
"Location 5": location_5 if location_5 else "N/A",    
}

我得到以下错误:

UnboundLocalError:分配前引用的局部变量"location_5">

注意:我正在使用带有JSON库的scroy

最简单的修复方法是将None或您的最终"N/a"值分配给except块中的每个变量,即:

try:
location_5 = schools['examInformation'][4]['cbrLocationShortName']
except:
location_5 = 'N/A'
yield {
"Location 5": location_5,   
}

如果你想避免你的例子中所有的代码重复和异常处理,我会用一个安全的方法把它打包成一个循环:

locations = {}
exam_information = schools['examInformation']
for i in range(len(exam_information)):
location_key = f'Location {i + 1}'
locations[location_key] = exam_information[i].get('cbrLocationShortName', 'N/A')
yield locations

相关内容

最新更新