问题:Twitter Streaming API - urllib3.exceptions.ProtocolError: ('连接中断: IncompleteRead

使用 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 u003d 设置为 True:

根据Incompleteread-error-when-retrieving-twitter-data-using-python

删除英语语言过滤器。

解答

解决了。

对于那些好奇或遇到类似问题的人:经过一些实验,我发现传入推文的积压是问题所在。每次系统收到一条推文时,我的系统都会运行一个实体识别和存储过程,这会花费一小段时间,并且随着收集数百到数千条推文的时间,这个积压越来越大,直到 API 无法处理它并且抛出了那个错误。

解决方案: 将“on_status/on_data/on_success”函数剥离到最基本的部分,并在流会话关闭后单独处理任何计算,即存储或实体标识。或者,您可以使您的计算更加高效,并使时间间隔变得不重要,这取决于您。

Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐