Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/277.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/actionscript-3/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在持续时间参数(行、秒、推等)后停止Tweepy流_Python_Twitter_Streaming_Tweepy_Duration - Fatal编程技术网

Python 在持续时间参数(行、秒、推等)后停止Tweepy流

Python 在持续时间参数(行、秒、推等)后停止Tweepy流,python,twitter,streaming,tweepy,duration,Python,Twitter,Streaming,Tweepy,Duration,我正在使用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)

我正在使用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条tweet后停止,3分钟后停止,文本输出文件达到150行后停止,等等。我知道套接字超时时间并不是用来实现这一点的

我看了一下这个类似的问题:

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

除了键盘中断之外,有人能根据一些用户输入参数提出停止Tweepy的方法吗(在此方法中使用流时)


谢谢

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

这是通过对计数器和停止值使用静态Python变量实现的(例如,抓取20条tweet后停止)。这目前是一个地理位置搜索,但您可以使用
getWeetsByHashTag()
方法轻松地将其替换为hashtag搜索

#!/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.
#/usr/bin/env python
从tweepy导入(流,OAuthHandler)
从tweepy.streaming导入StreamListener
类侦听器(StreamListener):
tweet_计数器=0#静态变量
def登录(自我):
用户密钥=
消费者的秘密=
访问令牌=
访问\u令牌\u机密=
auth=OAuthHandler(使用者密钥,使用者密钥)
授权设置\u访问\u令牌(访问\u令牌,访问\u令牌\u密钥)
返回授权
def on_状态(自身、状态):
Listener.tweet_计数器+=1
打印(str(Listener.tweet_counter)+’。屏幕名称=“%s”tweet=“%s”
%(status.author.screen_名称、status.text.replace('\n',''))
如果Listener.tweet_计数器
上述解决方案有助于通过hashtag获取tweet,尽管在定义getWeetByHashtag函数时出现了一个小错误。您使用了Listener.stopAt而不是Listener.stop_at=stop_at_number

我对代码进行了一些调整,因此您可以轻松地在指定的秒数内终止代码

定义了新函数init,以帮助调整秒数和“on_数据”,其中包含有关on_状态函数的更多信息

享受:

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 __init__(self, time_limit=8):
        self.start_time = time.time()
        self.limit = time_limit
        super(Listener, self).__init__()

    def on_data(self, data):
        Listener.tweet_counter += 1
        if (time.time() - self.start_time) < self.limit and Listener.tweet_counter < Listener.stop_at:
            print(str(Listener.tweet_counter)+data)
            return True
        else:
            print("Either Max number reached or time limit up at:"+ str(Listener.tweet_counter)+" outputs")
            self.saveFile.close()
            return False

    #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 and (time.time() - self.start_time) < self.limit:
            #return True
        
        #else:
            #print('Max num reached or time elapsed= ' + 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.stop_at = 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.
    listener.getTweetsByHashtag(1000,"hi")
来自tweepy导入的
(流,OAuthHandler)
从tweepy.streaming导入StreamListener
类侦听器(StreamListener):
tweet_计数器=0#静态变量
def登录(自我):
用户密钥=
消费者的秘密=
访问令牌=
访问\u令牌\u机密=
auth=OAuthHandler(使用者密钥,使用者密钥)
授权设置\u访问\u令牌(访问\u令牌,访问\u令牌\u密钥)
返回授权
定义初始(自身,时间限制=8):
self.start\u time=time.time()
self.limit=时间限制
超级(监听器,自我)。\uuuu init\uuuu()
def on_数据(自身、数据):
Listener.tweet_计数器+=1
如果(time.time()-self.start\u time)