【问题标题】:Python tweepy streamerPython tweepy 流光
【发布时间】:2020-07-02 18:20:48
【问题描述】:

我正在使用 on_data 函数运行 tweepy 流媒体,即使模式设置为 extended,我也无法获得完整的推文:当我运行 def on_data 时,仅传递 text 参数,然后我得到截断的推文,这很好,但是当我通过 full_text 时,我得到以下错误:KeyError: 'full_text'。我认为我在做我从 Tweepy API 文档中理解的事情,但我仍然遇到错误。有人可以帮我吗?

    def on_data(self, data):
        json_load = json.loads(data)
        tweet = json_load["full_text"]
        user = json_load["user"]["screen_name"]
        print(user, tweet)
        try:
            with open("data_file.txt", 'a') as df:
                df.write(tweet + "\n")
            return True
        except BaseException as e:
            print("Error on_data %s" % str(e))
        return True


# letting the user decide the subject
subj = input("please enter the hashtag to follow separated by commas: ")
stream_listener = MyStreamListener()
tweets = tweepy.Stream(auth = api.auth, listener=stream_listener, tweet_mode="extended")
tweets.filter(track=[subj], is_async=True)```

【问题讨论】:

    标签: python twitter tweepy


    【解决方案1】:

    在标准流 API 中,自动表示扩展推文,无需传递 tweet_mode="extended"(实际上此选项无效,将在流端点上被忽略 - 它仅适用于常规 REST 端点返回推文)。

    您应该会发现full_text 值位于名为extended_tweet 的推文数据的另一部分中。查看this answer

    你可以试试你现有的代码,例如

        tweet = json_load["extended_tweet"]["full_text"]
    

    或者,按照链接答案中的建议:

    def on_status(self, status):
        try:
            text = status.extended_tweet["full_text"]
        except AttributeError:
            text = status.text
    

    【讨论】:

    • 嗨@andy-piper,谢谢。我之前尝试过tweet = json_load["extended_tweet"]["full_text"],但我仍然收到KeyError,但我不明白为什么。
    • 另外,当尝试按照您的建议使用 on_status 时,我收到另一个错误:tweet_mode="extended"
    • 我想知道我是否将tweet_mode="extended" 放在正确的位置?现在我把它放在我的流的定义中,但似乎没有读取?
    • 我已经删除了 on_data 功能,我正在使用 on_status :类似这样的东西:text = status.extended_tweet["full_text"] 现在似乎可以工作了,我也很困惑,因为所有的转发 [RT ] 仍然限制在 140 个字符,所以我想我现在很好,谢谢。
    猜你喜欢
    • 2018-05-30
    • 1970-01-01
    • 2015-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-06
    • 1970-01-01
    • 2012-05-09
    相关资源
    最近更新 更多