こんにちは 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 ステートメントで囲む必要があると推測していますが、その方法を理解するのに苦労しています。
どんな助けでも大歓迎です。
編集:私は解決策を見つけたかもしれないと思いますが、それが特にエレガントかどうかはわかりません.....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