我想设置最大推文数限制

时间:2019-08-18 16:28:58

标签: python twitter-streaming-api

我对python非常陌生。我正在使用tweepy库通过Twitter流API抓取推文。但运行一个小时后,似乎连接断开。我想知道在断开连接之前是否有任何方法可以阻止程序运行。简而言之,限制推文。

我已经尝试过.items方法,但由于它的名称为Error,因此无法正常工作。

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


  ckey="xxxxxxxxxxxxxxxxxxxxxxxxxxx"
  csecret="xxxxxxxxxxxxxxxxxxxxxx"
  atoken="xxxxxxxxxxxxxxxxxxxxx"
  asecret="xxxxxxxxxxxxxxxxxxxxxxxxxxx"

  class listener(StreamListener):

    def on_data(self, data):
        print(data)
        return(True)

    def on_error(self, status):
       print status

  auth = OAuthHandler(ckey, csecret)
  auth.set_access_token(atoken, asecret)

  twitterStream = Stream(auth, listener())
  twitterStream.filter(track=["Obama"])

谢谢

1 个答案:

答案 0 :(得分:1)

要解决您的连接问题,请寻求帮助:

Tweepy Connection broken: IncompleteRead - best way to handle exception? or, can threading help avoid?

要获得tweets限制,可以在获取所需数量的tweet时从类return False中使用def on_data。在init方法中设置最大数量的推文,并使用try and except进行错误处理。这可能有帮助

def __init__(self):
    super().__init__()
    self.max_tweets = 10
    self.tweet_count = 0

def on_data(self, data):
    try:
     data
    except TypeError:
        print(completed)
    else:
     self.tweet_count+=1
     if(self.tweet_count==self.max_tweets):
       print("completed")
       return(False)
     else:
      decoded = json.loads(data)