"AttributeError: module 'tweepy' has no attribute 'StreamListener'" with Python 3.9

"AttributeError: module 'tweepy' has no attribute 'StreamListener'" with Python 3.9

class MyStreamListener(tweepy.StreamListener):
    def on_status(self, status):
        print(status.text)  # prints every tweet received

    def on_error(self, status_code):
        if status_code == 420:  # end of monthly limit rate (500k)
            return False

我使用 Python 3.9 并通过 pip 安装了 Tweepy。我在 class 行得到了 AttributeError。 我的导入只是 import tweepy。身份验证得到正确处理。 在 streaming.py 文件中,我有 class Stream。但是使用这个 class 就这样结束了。例如没有 status.text,即使有 on_status 函数。我有点困惑。

如果您查看模块,引用 StreamListener 的正确方法是 tweepy.streaming.StreamListener,而不是 tweepy.StreamListener

Tweepy v4.0.0 是最近发布的,它将 StreamListener 合并为 Stream

我建议将您的代码更新为子类 Stream
或者,您可以降级到 v3.10.0。

如@Harmon758 所述,他们在版本 4 之后将 StreamListener 合并到 Stream 中。此外,您不需要创建 api auth对象分开。这是代码:

from tweepy import Stream

class MyStreamListener(Stream):
    def on_status(self, status):
        print(status.text)  # prints every tweet received

    def on_error(self, status_code):
        if status_code == 420:  # end of monthly limit rate (500k)
            return False


stream = MyStreamListener('consumer_key',
                          'consumer_secret',
                          'access_token',
                          'access_token_secret')

stream.filter(track=["Python"], languages=["en"])