How to download twitter feed

夙愿已清 提交于 2019-12-25 09:26:06

问题


I am quite the novice when it comes to coding. How do I modify this sample code to download tweets using Python?

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 entered my keys.

I should be able to download tweets using a command like this print_tweets.py "Enter subject here" Where do I enter this command? In Python? In the command prompt?

I am getting this error:

NameError Traceback (most recent call last) in () ----> 1 print_tweets.py

NameError: name 'print_tweets' is not defined

Please help!


回答1:


The NameError is saying the python script isn't receiving command line arguments, sys.argv[1] being the "subject". Replace "Enter subject here" with the subject you wish to search.

In this example, springbreak is sys.argv[1]:

C:\> python print_tweets.py springbreak

should return and print out tweet texts containing your "subject".

You may also need to change:

if __name__ == "__version__":

to

if __name__ == "__main__":

as __main__ is the entry-point to the script.

The entire script:

#!/usr/bin/env python

import sys
import tweepy

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

if __name__ == "__main__":
    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)


来源:https://stackoverflow.com/questions/43219596/how-to-download-twitter-feed

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!