【问题标题】:Newest tweets on tweepy for python?tweepy for python 的最新推文?
【发布时间】:2015-09-27 19:55:56
【问题描述】:

我正在使用 tweepy 查找包含某个单词的推文,但我只想获取最近五分钟内的最新推文。我该怎么办?这是我目前的代码。

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)

【问题讨论】:

    标签: python twitter tweepy


    【解决方案1】:

    首先:我编辑了你的帖子以删除你的凭据,我建议你从 twitter 获取新的并且永远不要再分享它们。

    还将您的api.search(Rest API)更改为Streaming API。这将在您打开该连接的那一刻为您提供符合您的条件的部分推文。

    例如

    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)
    

    【讨论】:

    • 如何显示推文?这是我现在拥有的代码:consumer_key = ""``consumer_secret = "" auth = tweepy.OAuthHandler(consumer_key, consumer_secret) api = tweepy.API(auth) class MyStreamListener(tweepy.StreamListener): def on_status(self, status): print(status.text) myStreamListener = MyStreamListener() myStream = tweepy.Stream(auth=api.auth, listener=myStreamListener) consumer_key = "" consumer_secret = "" auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token("", "") print (myStream)
    • print(status.text) 正在显示实际的推文。删除print(myStream)。你没有收到任何东西吗?
    • 试试上面的代码,那是我自己用的和工作的。 print(str(status.text.encode('utf-8'))) 希望能解决您可能遇到的任何编码问题。 print(status_code) 将打印从推特上收到的任何代码 here
    猜你喜欢
    • 1970-01-01
    • 2018-11-08
    • 2013-11-11
    • 2017-07-31
    • 1970-01-01
    • 2012-03-08
    • 2018-06-29
    • 2022-08-11
    • 2012-07-23
    相关资源
    最近更新 更多