mehstg
mehstg

Reputation: 419

Tweepy python code returns KeyError on 'media' entity when tweet does not contain image

Hi people of StackOverflow

I am relatively new to Tweepy/Twitter API and am having a few issues getting it to return the URL's for images.

Basically, I have written a snippet of code that searches for tweets against a particular hashtag, then returns image URL entities that exist in the tweets. I am hitting an issue however when a tweet is returned that does not have any media in it. Error shown below:

Traceback (most recent call last):
File "./tweepyTest.py", line 18, in <module>
for image in  tweet.entities['media']:
KeyError: 'media'

Below is my code:

for tweet in tweepy.Cursor(api.search,q="#hashtag",count=5,include_entities=True).items(5):
        #print tweet.text
        for image in  tweet.entities['media']:
            print image['media_url']

I am guessing I need to encase the for loop in some kind of if statement, however I am struggling to get my head around how.

Any help would be much appreciated.

EDIT: I think I might have found a solution, however i'm not sure it is particularly elegant.....using a try/except.

for tweet in tweepy.Cursor(api.search,q="#hashtag",count=5,include_entities=True).items(5):
    #print tweet.text
    try:
            for image in  tweet.entities['media']:
                    print image['media_url']
    except KeyError:
            pass

Upvotes: 3

Views: 4889

Answers (1)

Blair
Blair

Reputation: 15788

You could check for the existence of the key:

for tweet in tweepy.Cursor(api.search,q="#hashtag",count=5,include_entities=True).items(5):
    #print tweet.text
    if 'media' in tweet.entities:
        for image in  tweet.entities['media']:
            print image['media_url']

Or get an empty list if there is no such key:

for tweet in tweepy.Cursor(api.search,q="#hashtag",count=5,include_entities=True).items(5):
    #print tweet.text
    for image in  tweet.entities.get('media', []):
        print image['media_url']

Upvotes: 3

Related Questions