Search code examples
pythontwitter

Unable to download twitter data


def get_tweets(api, input_query):
    for tweet in tweepy.Cursor(api.search, q=input_query,lang="en").items():
    yield tweet

if __name__ == "__version__":
    input_query = sys.argv[1]

    access_token = "REPLACE_YOUR_KEY_HERE"
    access_token_secret = "REPLACE_YOUR_KEY_HERE"
    consumer_key = "REPLACE_YOUR_KEY_HERE"
    consumer_secret = "REPLACE_YOUR_KEY_HERE"
    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)
    api = tweepy.API(auth)
    tweets = get_tweets(api, input_query)
    for tweet in tweets:
        print(tweet.text)

I am trying to download data from Twitter using the command prompt. I have entered my keys (I just recreated them all), saved the script as "print_tweets" and am entering "python print_tweets.py subject" into the command prompt but nothing is happening, no error message or anything.

I thought the problem might have to do with the path environment, but I created another program that prints out "hello world" and this executed without issue using the command prompt.

Can anyone see any obvious errors with my code above? Does this work for you? I've even tried changing "version" to "main" but this gives me an error message:

if name == "version":


Solution

  • It seems you are running the script in an ipython interpreter, which won't be receiving any command line arguments. Try this:

    import tweepy
    
    def get_tweets(api, input_query):
        for tweet in tweepy.Cursor(api.search, q=input_query,lang="en").items():
            yield tweet
    
    input_query = "springbreak"  # Change this string to the topic you want to search tweets
    
    access_token = "REPLACE_YOUR_KEY_HERE"
    access_token_secret = "REPLACE_YOUR_KEY_HERE"
    consumer_key = "REPLACE_YOUR_KEY_HERE"
    consumer_secret = "REPLACE_YOUR_KEY_HERE"
    
    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)
    api = tweepy.API(auth)
    tweets = get_tweets(api, input_query)
    for tweet in tweets:
        print(tweet.text)