使用 Python 获取 Twitter 位置时收到 ReadTimeOut 错误

Receiving ReadTimeOut Error when grabbing Twitter locations with Python

我 运行 以下代码 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:\Python27\Output2.csv", "w")
file.write("X,Y\n")

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) + "\n")

               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:\Python27\lib\site-packages\tweepy\streaming.py", line 445, in filter
    self._start(async)
  File "C:\Python27\lib\site-packages\tweepy\streaming.py", line 361, in _start
    self._run()
  File "C:\Python27\lib\site-packages\tweepy\streaming.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