我对Python很陌生。我正在使用 tweepy 库通过 Twitter 流 API 抓取推文。但运行一个小时后,连接似乎断开了。我想知道是否有任何方法可以在连接断开之前阻止程序运行。简而言之,限制推文。
我尝试过 .items 方法,但它不起作用,因为它给出了名称错误。
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"])
谢谢
最佳答案
要解决您的连接问题,请从此获取帮助:
要实现推文限制,当获取所需数量的推文时,您可以从类 def on_data
方法返回 False
。在 init
方法中设置最大推文数量,并使用 try 和 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)
关于python - 我想设置推文最大数量的限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57546419/