使用Twython流式传输推文时不断出现chunkedencodingerror
我刚开始学习编程,正在尝试通过使用Twython这个Twitter的封装库来获取推文,想要了解一下如何处理API和数据。但是每次我这样做的时候,都会遇到一个错误,大约在获取5000条推文的时候就会出问题。我用其他的库,比如python-twitter,进行流式获取时就能顺利获取到大约80万条推文,没有遇到类似的错误。
--------------------------------------------------------------------------
ChunkedEncodingError Traceback (most recent call last)
<ipython-input-5-fdcf34f23648> in <module>()
1 #[stream.statuses.filter(track='twitter')]
----> 2 stream.statuses.sample()
/Users/myusername/anaconda/lib/python2.7/site-packages/twython/streaming/types.pyc in sample(self, **params)
75 url = 'https://stream.twitter.com/%s/statuses/sample.json' \
76 % self.streamer.api_version
---> 77 self.streamer._request(url, params=params)
78
79 def firehose(self, **params):
/Users/myusername/anaconda/lib/python2.7/site-packages/twython/streaming/api.pyc in _request(self, url, method, params)
132 response = _send(retry_counter)
133
--> 134 for line in response.iter_lines(self.chunk_size):
135 if not self.connected:
136 break
/Users/myusername/anaconda/lib/python2.7/site-packages/requests/models.pyc in iter_lines(self, chunk_size, decode_unicode)
643
644 for chunk in self.iter_content(chunk_size=chunk_size,
--> 645 decode_unicode=decode_unicode):
646
647 if pending is not None:
/Users/myusername/anaconda/lib/python2.7/site-packages/requests/models.pyc in generate()
616 yield chunk
617 except IncompleteRead as e:
--> 618 raise ChunkedEncodingError(e)
619 except AttributeError:
620 # Standard file-like object.
ChunkedEncodingError: IncompleteRead(0 bytes read, 1 more expected)
我用来生成这个的代码如下。我知道这个代码缺少很多东西,包括处理这个特定错误的方法。
from twython import TwythonStreamer
import numpy as np
import pandas as pd
from requests.exceptions import ChunkedEncodingError
counter = 0
class MyStreamer(TwythonStreamer):
def on_success(self, data):
global counter
#if 'text' in data:
#print data['text'].encode('utf-8')
counter+=1
print counter
def on_error(self, status_code, data):
print status_code
# Want to stop trying to get data because of the error?
# Uncomment the next line!
# self.disconnect()
stream = MyStreamer(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
stream.statuses.sample()
其实现在我并不打算对推文做什么,只是想看看能否在没有错误的情况下让这个程序正常运行。
1 个回答
1
嗯,我没搞清楚是什么导致了这个错误,但如果我改一下最后几行代码,它就能正常工作了。像这样:
def streamed():
while True:
try:
stream = MyStreamer(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
stream.statuses.filter(track='twitter', stall_warnings=True)
except ChunkedEncodingError:
continue
streamed()
这样可以让程序在出错时重新启动。 我还需要在
return True
这个类里的函数中添加一些东西。
之前这个回答也帮了我:如果出错,如何重新启动tweepy脚本?