用于Twitter API的Python Tweepy返回'错误401:未经授权的'

时间:2016-06-21 09:57:29

标签: python api twitter tweepy

以下代码在过去6个月内完美地用于检索某些Twitter帐户的关注者。突然,今天早上,代码停止工作返回错误401:未经授权'。

我在dev.twitter.com上查看了我的应用程序,它仍然有效。我更新了Tweepy。不知道为什么这不再起作用了。

代码在' Cursor.next'上失败线。

import tweepy
import mysql.connector
import time

consumer_key = 'secretkey'
consumer_secret = 'secretsecret'
access_token = 'secrettoken'
access_token_secret = 'secrettokensecret'
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)



for twit_name in twit_name_array:
 api = tweepy.API(auth)
 t0= time.clock()

 data = api.rate_limit_status()
 user_followers_remaining = data['resources']['followers']['/followers/ids']['remaining']
 print(user_followers_remaining)
 id_i = twit_name[1]

 countpage = 0
 countx = 0

 def limit_handled(cursor):
    while True:
        data = api.rate_limit_status()
        user_followers_remaining = data['resources']['followers']['/followers/ids']['remaining']

        if user_followers_remaining>0:
            try:
                yield cursor.next()
            except BaseException as e:
                print('failed_on_CURSOR_NEXT', str(e))
                global api
                api = tweepy.API(auth)
                try:
                    yield cursor.next()
                except BaseException as e:
                    print('failed_on_CURSOR_NEXT_2', str(e))
                    break
        else:
            for min_remain in range(-3, 0):
                print('##### TIMEOUT #####  -----  Out of queries, waiting ' + str(min_remain*5) + 'min')
                time.sleep(5*60)

1 个答案:

答案 0 :(得分:0)

正如@ advance512所述,我不得不再次登录才能解决这个问题。下面这段代码就是这个诀窍:

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)

def limit_handled(cursor):
    while True:
        try:
            yield cursor.next()
        except BaseException as e:
            print('failed_on_CURSOR_NEXT', str(e))
            time.sleep(5)
            global api
            api = tweepy.API(auth)
            yield cursor.next()

for followers in limit_handled(tweepy.Cursor(api.followers_ids, id = id_i).pages()):
    for fll in followers:
        process_follower(fll)