gpt4 book ai didi

python - 使用Python抓取Twitter位置时收到ReadTimeOut错误

转载 作者:行者123 更新时间:2023-12-03 08:24:05 24 4
gpt4 key购买 nike

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

关于python - 使用Python抓取Twitter位置时收到ReadTimeOut错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48042637/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com