Tweepy python code returns KeyError on 'media&

2019-05-26 01:04发布

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

1条回答
兄弟一词,经得起流年.
2楼-- · 2019-05-26 01:36

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']
查看更多
登录 后发表回答