我对python非常陌生。我正在使用tweepy库通过Twitter流API抓取推文。但运行一个小时后,似乎连接断开。我想知道在断开连接之前是否有任何方法可以阻止程序运行。简而言之,限制推文。
我已经尝试过.items方法,但由于它的名称为Error,因此无法正常工作。
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"])
谢谢
答案 0 :(得分:1)
要解决您的连接问题,请寻求帮助:
要获得tweets限制,可以在获取所需数量的tweet时从类return False
中使用def on_data
。在init
方法中设置最大数量的推文,并使用try and 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)