我正在制作一个文本搜索程序以开始使用tweepy。我遇到了一个我似乎无法解决的错误。完整的错误消息如下所示。
Traceback (most recent call last):
File "/Users/nattaylor/Documents/Programming/Python/twitterapi.py", line 53, in <module>
myStream.filter(track=['Warriors'])
File "/anaconda3/lib/python3.6/site-packages/tweepy/streaming.py", line 450, in filter
self._start(async)
File "/anaconda3/lib/python3.6/site-packages/tweepy/streaming.py", line 364, in _start
self._run()
File "/anaconda3/lib/python3.6/site-packages/tweepy/streaming.py", line 297, in _run
six.reraise(*exc_info)
File "/anaconda3/lib/python3.6/site-packages/six.py", line 693, in reraise
raise value
File "/anaconda3/lib/python3.6/site-packages/tweepy/streaming.py", line 266, in _run
self._read_loop(resp)
File "/anaconda3/lib/python3.6/site-packages/tweepy/streaming.py", line 327, in _read_loop
self._data(next_status_obj)
File "/anaconda3/lib/python3.6/site-packages/tweepy/streaming.py", line 300, in _data
if self.listener.on_data(data) is False:
File "/anaconda3/lib/python3.6/site-packages/tweepy/streaming.py", line 54, in on_data
status = Status.parse(self.api, data)
AttributeError: 'MyStreamListener' object has no attribute 'api'
我的代码在这里:
from tweepy import OAuthHandler
import tweepy
from tweepy import StreamListener
from tweepy import Stream
import time
consumer_key = 'cant show you these'
consumer_secret = 'Im so desperate ive been working on this for so long'
access_token = 'its not even very hard'
access_secret = 'I just suck'
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_secret)
api = tweepy.API(auth)
print('')
class MyStreamListener(tweepy.StreamListener):
def __init__(self):
#initializes the counter
self.counter = 0
def on_status(self, status):
#prints status text. Also counts the mentions.
self.counter = self.counter + 1
print(status.text)
def on_error(self, status_code):
if status_code == 420:
print('420 error')
#Ends stream in case of rate limiting
return False
myStreamListener = MyStreamListener()
myStream = tweepy.Stream(auth = api.auth, listener = myStreamListener)
#Word
myStream.filter(track=['Warriors'])
我认为在某处我的tweepy语法一定是个问题。任何输入都非常感谢。 (我很失落,困惑和害怕,请你们比我更了解我需要你)
答案 0 :(得分:0)
正如您所导入的那样
import tweepy
from tweepy import StreamListener
from tweepy import Stream
尝试继承StreamListener而不是tweepy.StreamListener
替换
class MyStreamListener(tweepy.StreamListener):
带
class MyStreamListener(StreamListener):
为了更好的衡量,请从
更改您的init方法def __init__(self):
#initializes the counter
self.counter = 0
到
def __init__(self):
super().__init__()
#initializes the counter
self.counter = 0
来自tweepy的消息来源
https://github.com/tweepy/tweepy/blob/master/tweepy/streaming.py
...
from tweepy.api import API
...
class StreamListener(object):
def __init__(self, api=None):
self.api = api or API()
...
你可能会离开&#34;只更新 init 方法来初始化父对象,但最好选择一个导入,如果你显式导入StreamListener,你也可以使用它来代替完整的tweepy导入。 / p>