当推文不包含图像时,Tweepy python代码在"媒体"实体上返回KeyError



嗨,StackOverflow 的人们

我对Tweepy/Twitter API相对较新,并且在让它返回图像的URL时遇到了一些问题。

基本上,我编写了一段代码,用于针对特定主题标签搜索推文,然后返回推文中存在的图像 URL 实体。但是,当返回没有任何媒体的推文时,我遇到了一个问题。错误如下所示:

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

下面是我的代码:

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']

我猜我需要将 for 循环括在某种 if 语句中,但是我正在努力弄清楚如何。

任何帮助将不胜感激。

编辑:我想我可能已经找到了解决方案,但我不确定它是否特别优雅......使用尝试/例外。

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

您可以检查密钥是否存在:

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']

或者,如果没有这样的键,则获取一个空列表:

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']

最新更新