Reputation: 77
I am trying to scrape some results from ebay with python and I am running into an error :
condition = item['condition'][0]['conditionDisplayName'][0]
>>> KeyError: 'condition'`
This is the code in question :
for item in (parseddoc["findItemsByKeywordsResponse"][0] ["searchResult"][0]["item"]):
condition = item['condition'][0]['conditionDisplayName'][0]
print(condition)
I am trying to figure out a way to stop it from getting the error and just default to a preset value( "N/A" for example )
and continue with the loop. What's the best way to achieve that? Thanks
Upvotes: 1
Views: 594
Reputation: 164623
Use a try
/ except
clause to catch KeyError
:
for item in parseddoc["findItemsByKeywordsResponse"][0]["searchResult"][0]["item"]:
try:
condition = item['condition'][0]['conditionDisplayName'][0]
except KeyError:
condition = 'N/A'
print(condition)
Upvotes: 3
Reputation: 22827
Add the following if/else statement to your loop:
for item in (parseddoc["findItemsByKeywordsResponse"][0]["searchResult"][0]["item"]):
if 'condition' not in item:
condition = 'N/A'
else:
condition = item['condition'][0]['conditionDisplayName'][0]
print(condition)
Upvotes: 0