Python Twitter 的 Tweepy API returns 'error 401 : Unauthorized'

Python Tweepy for Twitter API returns 'error 401 : Unauthorized'

在过去的 6 个月中,以下代码在检索某些 Twitter 帐户的关注者方面运行良好。今天早上突然,代码停止工作返回 'Error 401 : Unauthorized'。

我在 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)

如@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)