使用Python获取Twitter位置时接收ReadTimeOut错误
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用Python获取Twitter位置时接收ReadTimeOut错误相关的知识,希望对你有一定的参考价值。
我正在使用python运行以下代码来获取特定边界框的twitter位置:
import json
from tweepy import Stream
from tweepy import OAuthHandler
from tweepy.streaming import StreamListener
#Enter Twitter API Key information
consumer_key = ''
consumer_secret = ''
access_secret = ''
file = open("C:Python27Output2.csv", "w")
file.write("X,Y
")
data_list = []
count = 0
class listener(StreamListener):
def on_data(self, data):
global count
#How many tweets you want to find, could change to time based
if count >= 0:
json_data = json.loads(data)
coords = json_data["coordinates"]
if coords is not None:
print coords["coordinates"]
lon = coords["coordinates"][0]
lat = coords["coordinates"][1]
data_list.append(json_data)
file.write(str(lon) + ",")
file.write(str(lat) + "
")
count += 1
return True
else:
file.close()
return False
def on_error(self, status):
print status
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_secret)
twitterStream = Stream(auth, listener())
#What you want to search for here
twitterStream.filter(locations=[10.01,46.85,13.09,49.43])
这很好用,我得到坐标。但是,每次程序停止后,我都会收到一个读取超时错误,如下所示:
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
import UrbanTweets
File "UrbanTweets.py", line 52, in <module>
twitterStream.filter(locations=[10.01,46.85,13.09,49.43])
File "C:Python27libsite-packages weepystreaming.py", line 445, in filter
self._start(async)
File "C:Python27libsite-packages weepystreaming.py", line 361, in _start
self._run()
File "C:Python27libsite-packages weepystreaming.py", line 294, in _run
raise exception
ReadTimeoutError: HTTPSConnectionPool(host='stream.twitter.com', port=443): Read timed out.
有谁知道如何解决这个问题?
非常感谢!
答案
我测试了你的代码,它工作正常(我在OSX,Python 2.7上测试过。)所以我无法重现你的错误。也许你只是面对互联网连接问题?你需要等多久才能得到这个错误?
您可以在此处添加try-catch异常块:
while True:
try:
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_secret)
twitterStream = Stream(auth, listener())
#What you want to search for here
twitterStream.filter(locations=[10.01,46.85,13.09,49.43])
except Exception as e:
#Handle expception here (print, pass, break..?)
print e
pass
以上是关于使用Python获取Twitter位置时接收ReadTimeOut错误的主要内容,如果未能解决你的问题,请参考以下文章
设置在某个 Twitter 用户使用他们以前未使用过的主题标签时接收电子邮件