How to get media_url from tweets using the Tweepy API
Question: I am using this code:

    
    
    import tweepy
    from tweepy.api import API
    import urllib
    import os
    
    i = 1
    consumer_key="xx"
    consumer_secret="xx"
    access_token="xx"
    access_token_secret="xx"
    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    auth.secure = True
    auth.set_access_token(access_token, access_token_secret)
    api = tweepy.API(auth)
    
    class MyStreamListener(tweepy.StreamListener):
    def __init__(self, api=None):
        self.api = api or API()
        self.n = 0
        self.m = 10
    
    def on_status(self, status):
        if 'media' in status.entities:
            for image in  status.entities['media']:
                global i
                #picName = status.user.screen_name
                picName = "pic%s.jpg" % i
                i += 1
                link = image['media_url']
                filename = os.path.join("C:/Users/Charbo/Documents/Python/",picName)
                urllib.urlretrieve(link,filename)
                #use to test
                print(status.user.screen_name)
    
        else: 
            print("no media_url")
    
        self.n = self.n+1
    
        if self.n < self.m: 
            return True
        else:
            print ('tweets = '+str(self.n))
            return False
    
    def on_error(self, status):
        print (status)
    
    myStreamListener = MyStreamListener()
    myStream = tweepy.Stream(auth, MyStreamListener(),timeout=30)
    myStream.filter(track=['#feelthebern'])
    

I am trying the access the media_url under 'photo' in my dictionary. But I am
getting the following error: 'dict' object has no attribute 'media'. I would
appreciate help navigating the JSON.

Thanks in advance!


Answer: You should try two things :

  * Add entities to your request

>

    
    
    tweepy.Cursor(api.search, q="#hashtag", count=5, include_entities=True)
    

  * Check if media is not nul : 

>

    
    
    if 'media' in tweet.entities:
        for image in  tweet.entities['media']:
            (do smthing with image['media_url'])
    

Hope this will help

