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

问题描述 投票:0回答:1

我正在使用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.

有谁知道如何解决这个问题?

非常感谢!

python twitter error-handling timeout tweepy
1个回答
1
投票

我测试了你的代码,它工作正常(我在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
© www.soinside.com 2019 - 2024. All rights reserved.