Skip to main content
 首页 » 编程设计

python之在持续时间参数(# 行、秒、#Tweets 等)后停止 Tweepy 流

2024年10月25日9pengyingh

我正在使用 Tweepy 捕获基于标签#WorldCup 的流式推文,如下面的代码所示。它按预期工作。

class StdOutListener(StreamListener): 
  ''' Handles data received from the stream. ''' 
 
  def on_status(self, status): 
      # Prints the text of the tweet 
      print('Tweet text: ' + status.text) 
 
      # There are many options in the status object, 
      # hashtags can be very easily accessed. 
      for hashtag in status.entries['hashtags']: 
          print(hashtag['text']) 
 
      return true 
 
    def on_error(self, status_code): 
        print('Got an error with status code: ' + str(status_code)) 
        return True # To continue listening 
 
    def on_timeout(self): 
        print('Timeout...') 
        return True # To continue listening 
 
if __name__ == '__main__': 
   listener = StdOutListener() 
   auth = tweepy.OAuthHandler(consumer_key, consumer_secret) 
   auth.set_access_token(access_token, access_token_secret) 
 
   stream = Stream(auth, listener) 
   stream.filter(follow=[38744894], track=['#WorldCup']) 

因为这是目前的热门话题标签,搜索不会花费太长时间来捕获 Tweepy 允许您在一次交易中获得的最大推文数量。但是,如果我要在#StackOverflow 上搜索,它可能会慢得多,因此,我想要一种终止流的方法。我可以在几个参数上执行此操作,例如在 100 条推文后停止、在 3 分钟后停止、在文本输出文件达到 150 行后等。我知道套接字超时时间不用于实现此目的。

我看过这个类似的问题:

Tweepy Streaming - Stop collecting tweets at x amount

但是,它似乎没有使用流式 API。它收集的数据也非常困惑,而这个文本输出是干净的。

除了键盘中断之外,任何人都可以根据一些用户输入参数提出停止 Tweepy 的方法(在此方法中使用流时)?

谢谢

请您参考如下方法:

我解决了这个问题,所以我将成为能够回答自己问题的互联网英雄之一。

这是通过为计数器和停止值使用静态 Python 变量来实现的(例如,在你抓取 20 条推文后停止)。目前这是一个地理定位搜索,但您可以使用 getTweetsByHashtag() 方法轻松地将其替换为主题标签搜索。

#!/usr/bin/env python 
from tweepy import (Stream, OAuthHandler) 
from tweepy.streaming import StreamListener 
 
class Listener(StreamListener): 
 
    tweet_counter = 0 # Static variable 
 
    def login(self): 
        CONSUMER_KEY = 
        CONSUMER_SECRET = 
        ACCESS_TOKEN = 
        ACCESS_TOKEN_SECRET = 
 
        auth = OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) 
        auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET) 
        return auth 
 
    def on_status(self, status): 
        Listener.tweet_counter += 1 
        print(str(Listener.tweet_counter) + '. Screen name = "%s" Tweet = "%s"' 
              %(status.author.screen_name, status.text.replace('\n', ' '))) 
 
        if Listener.tweet_counter < Listener.stop_at: 
            return True 
        else: 
            print('Max num reached = ' + str(Listener.tweet_counter)) 
            return False 
 
    def getTweetsByGPS(self, stop_at_number, latitude_start, longitude_start, latitude_finish, longitude_finish): 
        try: 
            Listener.stop_at = stop_at_number # Create static variable 
            auth = self.login() 
            streaming_api = Stream(auth, Listener(), timeout=60) # Socket timeout value 
            streaming_api.filter(follow=None, locations=[latitude_start, longitude_start, latitude_finish, longitude_finish]) 
        except KeyboardInterrupt: 
            print('Got keyboard interrupt') 
 
    def getTweetsByHashtag(self, stop_at_number, hashtag): 
        try: 
            Listener.stopAt = stop_at_number 
            auth = self.login() 
            streaming_api = Stream(auth, Listener(), timeout=60) 
            # Atlanta area. 
            streaming_api.filter(track=[hashtag]) 
        except KeyboardInterrupt: 
            print('Got keyboard interrupt') 
 
listener = Listener() 
listener.getTweetsByGPS(20, -84.395198, 33.746876, -84.385585, 33.841601) # Atlanta area.