Twitter Streaming API没有给出任何结果

时间:2016-07-02 08:33:57

标签: python python-2.7 twitter tweepy

我正在运行以下代码,以获取与以下关键字相关的推文。

from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream

access_token = "K"
access_token_secret = ""
consumer_key = ""
consumer_secret = ""

class StdOutListener(StreamListener):

    def on_data(self, data):
        print data
        return True

    def on_error(self, status):
        print status.text               

if __name__ == '__main__':

    l = StdOutListener()
    auth = OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)
    stream = Stream(auth, l)


    stream.filter(track=["flyspicejet","jetairways","airindiain","goairlinesindia","airvistara","spicejet","airindia","goairlines","vistara"])

然而,我跑了几个小时但没有结果!怎么可能没有发布这些关键字(印度流行的航空公司)的单一推文?

我做错了什么?

提前多多感谢。

1 个答案:

答案 0 :(得分:0)

您未正确处理错误案例。请尝试以下代码:

Python 3版本:

import time
import argparse
import os
import sys
import json

#Import the necessary methods from tweepy library
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
from http.client import IncompleteRead


access_token = "acc token here"
access_token_secret = "acc token secret"
consumer_key = "consumer key"
consumer_secret = "consumer secret here"

class StdOutListener(StreamListener):
    '''A basic listener that just writes received tweets to file.'''

    def __init__(self, outputfile):
        self.file = outputfile

    def on_data(self, data):
        with open(self.file, 'a') as ofile:
            #simply write everything to file as raw json
            ofile.write(data)
        return True

    def on_error(self, status):
        print(status)


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    requiredArgs = parser.add_argument_group('must need arguments')
    requiredArgs.add_argument('-o', '--output', help='Output txt file to write tweets', required=True)
    args = parser.parse_args()

    filepath = os.getcwd() + os.path.sep + args.output
    if os.path.exists(filepath):
        sys.exit("output file already exists; Give new filename!")
    else:
        #create an empty file
        open(args.output,'a').close()

    l = StdOutListener(args.output)
    auth = OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)

    keyword_list = ['Computer Science', 'Cancer', 'Germany', 'Paris']

    while True:
        try:
            stream = Stream(auth, l)
            stream.filter(track=keyword_list, stall_warnings=True)

        except IncompleteRead as e:
            # Oh well, sleep sometime & reconnect and keep trying again
            time.sleep(15)
            continue

        except KeyboardInterrupt:
            stream.disconnect()
            break