【发布时间】:2019-04-18 23:51:31
【问题描述】:
使用 tweepy 运行 python 脚本,该脚本在英语推文的随机样本中流式传输(使用 twitter 流 API)一分钟,然后交替搜索(使用 twitter 搜索 API)一分钟,然后返回。我发现的问题是大约 40 多秒后流式传输崩溃并出现以下错误:
完全错误:
urllib3.exceptions.ProtocolError: ('连接中断: IncompleteRead(0 bytes read)', IncompleteRead(0 bytes read))
读取的字节数可以在 0 到 1000 之间变化。
第一次看到流过早中断并且搜索功能提前启动时,搜索功能完成后它再次返回流,并且在此错误的第二次重复出现时代码崩溃。
我运行的代码是:
# Handles date time calculation
def calculateTweetDateTime(tweet):
tweetDateTime = str(tweet.created_at)
tweetDateTime = ciso8601.parse_datetime(tweetDateTime)
time.mktime(tweetDateTime.timetuple())
return tweetDateTime
# Checks to see whether that permitted time has past.
def hasTimeThresholdPast():
global startTime
if time.clock() - startTime > 60:
return True
else:
return False
#override tweepy.StreamListener to add logic to on_status
class StreamListener(StreamListener):
def on_status(self, tweet):
if hasTimeThresholdPast():
return False
if hasattr(tweet, 'lang'):
if tweet.lang == 'en':
try:
tweetText = tweet.extended_tweet["full_text"]
except AttributeError:
tweetText = tweet.text
tweetDateTime = calculateTweetDateTime(tweet)
entityList = DataProcessing.identifyEntities(True, tweetText)
DataStorage.storeHotTerm(entityList, tweetDateTime)
DataStorage.storeTweet(tweet)
def on_error(self, status_code):
def on_error(self, status_code):
if status_code == 420:
# returning False in on_data disconnects the stream
return False
def startTwitterStream():
searchTerms = []
myStreamListener = StreamListener()
twitterStream = Stream(auth=api.auth, listener=StreamListener())
global geoGatheringTag
if geoGatheringTag == False:
twitterStream.filter(track=['the', 'this', 'is', 'their', 'though', 'a', 'an'], async=True, stall_warnings=True)
if geoGatheringTag == True:
twitterStream.filter(track=['the', 'this', 'is', 'their', 'though', 'a', 'an', 'they\'re'],
async=False, locations=[-4.5091, 55.7562, -3.9814, 55.9563], stall_warnings=True)
# ----------------------- Twitter API Functions ------------------------
# XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
# --------------------------- Main Function ----------------------------
startTime = 0
def main():
global startTime
userInput = ""
userInput.lower()
while userInput != "-1":
userInput = input("Type ACTiVATE to activate the Crawler, or DATABASE to access data analytic option (-1 to exit): \n")
if userInput.lower() == 'activate':
while(True):
startTime = time.clock()
startTwitterStream()
startTime = time.clock()
startTwitterSearchAPI()
if __name__ == '__main__':
main()
我已经删除了搜索功能和数据库处理方面,因为它们是独立的,以避免代码混乱。
如果有人知道为什么会发生这种情况以及我如何解决它,请告诉我,我很想知道任何见解。
我尝试过的解决方案:
带有 http.client.IncompleteRead:
的 Try/Except 块
根据Error-while-fetching-tweets-with-tweepy
将 Stall_Warning = 设置为 True:
根据Incompleteread-error-when-retrieving-twitter-data-using-python
删除英语过滤器。
【问题讨论】:
标签: python twitter tweepy twitter-streaming-api