1

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

3
  • Lookup defaultdict Commented Oct 12, 2018 at 10:15
  • A defaultdict would generate the "condition" key, not default to somthing other if not present Commented Oct 12, 2018 at 10:15
  • consider putting your condition = in a try block and if exception is thrown change value to "N/A" Commented Oct 12, 2018 at 10:16

2 Answers 2

3

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) 
Sign up to request clarification or add additional context in comments.

Comments

0

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) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.