我编写了这个脚本来使用Twitter API来推送推文:
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
import random
import os
import twitter
import json
from twitter import *
import logging
ckey = 'xxx'
csecret = 'xxx'
atoken = 'xxx'
asecret = 'xxx'
count = 0
class listener(StreamListener):
def on_data(self, data):
global count
if count <= 10000000000:
json_data = json.loads(data)
coords = json_data.get("coordinates")
tweet = data.split(',"text":"')[1].split('","source')[0]
time = data.split('"created_at":"')[1].split('","id')[0]
userid = data.split('"id_str":"')[1].split('","text')[0]
if coords is not None:
xy = coords["coordinates"]
lon = coords["coordinates"][0]
lat = coords["coordinates"][1]
print "Time: " + str(time)
print "Tweet: " + str(tweet)
print "User ID: " + str(userid)
print "Coordinates: " + str(xy)
count += 1
if coords is None:
location = data.split (',"location":"')[1].split('","url')[0]
print "Time: " + str(time)
print "Tweet: " + str(tweet)
print "User ID: " + str(userid)
print "Location: " + str(location)
count += 1
return True
else:
return False
def on_error(self, status):
print status
auth = OAuthHandler(ckey, csecret)
auth.set_access_token(atoken, asecret)
def start_stream():
while True:
try:
twitterStream = Stream(auth, listener(), timeout=30.0)
twitterStream.filter(locations=[-125,25,-65,48], async=False)
except:
logging.exception('Got exception on main handler')
continue
start_stream()
问题是我一直得到IndexError:list index超出范围&#34;经常出错:
Traceback (most recent call last):
File "C:\Users\Username\Desktop\tweepy_test.py", line 67, in start_stream
twitterStream.filter(locations=[-125,25,-65,48], async=False)
File "C:\Python27\ArcGIS10.2\lib\site-packages\tweepy\streaming.py", line 421, in filter
self._start(async)
File "C:\Python27\ArcGIS10.2\lib\site-packages\tweepy\streaming.py", line 338, in _start
self._run()
File "C:\Python27\ArcGIS10.2\lib\site-packages\tweepy\streaming.py", line 278, in _run
raise exception
IndexError: list index out of range
我不确定出了什么问题,我应该在哪里查看以解决问题。由于在短时间内登录尝试次数过多,我希望能够修复此问题以避免error 420。通常,当我收到此IndexErrror消息时,Python会抛出错误420并停止流式传输。