python - 我想设置推文最大数量的限制

标签 python twitter-streaming-api

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

我尝试过 .items 方法,但它不起作用,因为它给出了名称错误。

  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"])

谢谢

最佳答案

要解决您的连接问题,请从此获取帮助:

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

要实现推文限制,当获取所需数量的推文时,您可以从类 def on_data 方法返回 False。在 init 方法中设置最大推文数量,并使用 try 和 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)

关于python - 我想设置推文最大数量的限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57546419/

相关文章:

http - Twitter 在 w3c 上的流式 API 方法

java - 与远程服务 Stream API 连接

python - PySide2 中 QScxmlStateMachine.connectToEvent 的奇怪行为

Python - Pandas - 导入 Excel 文件,遍历每一行,添加新值,并添加到数据框

python - 从 C++ 调用 Python 或 Lua 来计算表达式,仅在需要时计算未知变量

web-applications - 情感分析使推文与搜索查询匹配并进行分析

hadoop - 如何获取特定位置(印度)的推文?

python - 仅按语言过滤 Twitter 提要

python - 如果第二列与给定的 Pandas 列表匹配,则替换数据框列中的值

python - 通过 pool.map_async 进行多处理对于大数据帧来说非常慢