简体   繁体   中英

Newest tweets on tweepy for python?

I'm using tweepy to find tweets containing a certain word, but I want to just get the newest tweets from the last five minutes up. How would I go about this? This is my code at the moment.

import tweepy

consumer_key = "**********"
consumer_secret = "**********"

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token("**********", "**********")

api = tweepy.API(auth)

public_tweets = api.search(q = "", since = "2015-09-26", language = "EN")
for tweet in public_tweets:
    print(tweet.text)

First of all: I edited your post to remove your credentials, I would suggest you get new ones from twitter and never share them again.

Also change your api.search (Rest API) to the Streaming API . This will give you a portion of tweets that match your criteria for the moment you open that connection.

For example

from tweepy import Stream
from tweepy import OAuthHandler
from tweepy.streaming import StreamListener

consumer_key = '****'
consumer_secret = '****'
access_token = '****'
access_secret = '****'


class Listener(StreamListener):

    def on_status(self, status):

        try:

            print(str(status.text.encode('utf-8')))

        except Exception as e:
            print(e)

    def on_error(self, status_code):
        print(status_code)


while True:
    try:
        auth = OAuthHandler(consumer_key, consumer_secret)
        auth.set_access_token(access_token, access_secret)
        twitterStream = Stream(auth, Listener())

        twitterStream.filter(q=['python'])

    except Exception as e:
        print(e)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM