无法导入 StreamListener

Can't import StreamListener

我正在尝试使用 Twitter API 在 Python 中创建数据流,但我无法正确导入 StreamListener

这是我的代码:

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

class MyListener(StreamListener):
 
    def on_data(self, data):
        try:
            with open('python.json', 'a') as f:
                f.write(data)
                return True
        except BaseException as e:
            print("Error on_data: %s" % str(e))
        return True
 
    def on_error(self, status):
        print(status)
        return True
 
twitter_stream = Stream(auth, MyListener())
twitter_stream.filter(track=['#python'])

我收到这个错误:

Traceback (most recent call last):
  File "c:\Users\User\Documents\GitHub\tempCodeRunnerFile.python", line 6, in <module>
    from tweepy.streaming import StreamListener
ImportError: cannot import name 'StreamListener' from 'tweepy.streaming' (C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\tweepy\streaming.py)

Tweepy v4.0.0 昨天发布,并将 StreamListener 合并为 Stream

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

对于Tweepy v4,您不需要使用StreamListener。以下是 v4 的编辑代码:

import tweepy

class MyListener(tweepy.Stream):
    def on_data(self, data):
        try:
            with open('python.json', 'a') as f:
                f.write(data)
                return True
        except BaseException as e:
            print("Error on_data: %s" % str(e))
        return True
 
    def on_error(self, status):
        print(status)
        return True
 
twitter_stream = MyListener(
  "Consumer Key here", "Consumer Secret here",
  "Access Token here", "Access Token Secret here"
)
twitter_stream.filter(track=['#python'])

稍作调整即可解决此问题

#from tweepy.streaming import StreamListener #OLD CODE

import tweepy # NEW CODE

#class TweetListener (StreamListener): #OLD CODE

class TweetListener (tweepy.Stream): # NEW CODE