当我知道密钥存在时,如何处理PythonJSON密钥错误?

问题描述

我正在尝试运行以下代码,我知道键“ vin”存在,但始终收到键错误。如何在代码中处理此问题?

#page_url = 'https://www.cargurus.com/Cars/inventorylisting/viewDetailsFilterViewInventoryListing.action?zip=32805&inventorySearchWidgetType=PRICE&maxPrice=42500&maxMileage=50000&showNegotiable=false&sortDir=DESC&sourceContext=carGurusHomePageModel&distance=100&minPrice=0&sortType=PRICE&minMileage=0&sellerTypes=PRIVATE'

data = []
offset = 0
while True:
    print('Offset {}...'.format(offset))
    json_data = requests.get(page_url.format(offset)).json()
    
    for listing in json_data:
        jdata = requests.get(page_url.format(offset)).json()
        listing_title = listing['listingTitle']
        vehicle_id = listing['id']
        price = listing['price']
        year = listing['carYear']
        make_name = listing['makeName']
        model_name = listing['modelName']
        mileage = listing['mileage']
        vin = listing['vin']
        
        # ... other data

        #print((jdata,listing_title,vehicle_id,price,year,make_name,model_name,mileage,vin))

解决方法

更改代码的最后一行,如下所示:

try:
    vin = listing['vin']
except KeyError:
    print(f"'vin' not found in {listing}")

这将向您显示(1)密钥实际上并不存在于所有数据项中,只有它们中的 some 个; (2)如何在代码中处理此问题。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...