tweepy 无法连接到推特 - 没有返回错误

tweepy unable to connect to twitter- No error returned

我是 python 的初学者。我正在尝试从 Twitter 获取给定用户句柄的关注者数量。问题是 tweepy 没有连接到 Twitter,甚至没有返回任何错误。终端只是保持空白。请帮忙解决这个问题。

import tweepy
import pymysql
import time

#insert your Twitter keys here
consumer_key =''
consumer_secret=''
access_token=''
access_secret=''

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

global conn
conn=pymysql.connect(db='twitter', user='root' , host= 'localhost' , port=3307)
global cursor
cursor=conn.cursor()
print("entering loop")

while True:
    query=cursor.execute("select twitter_name from timj_users where found_followers is null and twitter_name is not null order by id asc limit 1")
    if query>0:
        results=cursor.fetchone()
        timj_handle=results[0]
        user = tweepy.Cursor(api.followers, screen_name=timj_handle).items()
        try:
            followers=user.follower_count
            location=user.location
            cursor.execute("update timj_users set followers=%s,location=%s,found_followers=1 where twitter_name=%s" , (followers, location ,handle))
            conn.commit()
            print("user followers received")
            if followers>100:
                user.follow()
                cursor.execute("update users set followed=1 where twitter_name=%s" , (handle))
                conn.commit()
                print("User followed")
        except:
            time.sleep(15*60)
            print 'We got a timeout ... Sleeping for 15 minutes'

    else:
        print("All users processed")
        break

看起来像这条线

auth = tweepy.auth.OAuthHandler(consumer_key, consumer_secret)

应该是

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)

但是,你写的对于初学者来说真的很复杂。我可以建议你 运行 一个更基本的 Tweepy 程序,看看你会得到什么。

import tweepy

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

api = tweepy.API(auth)

public_tweets = api.home_timeline()
for tweet in public_tweets:
    print tweet.text

(来自Tweepy Documentation)

如果您没有收到来自 python 的错误并且控制台只是 "hanging" 您确实连接到了 Twitter,但是由于代码中没有显示任何消息的内容从 Twitter 获取你不会收到任何东西。

您需要在代码中包含:

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

该代码将为您提供与 Twitter 相关的号码 Error Codes & Responses

更清楚:

    except:
        time.sleep(15*60)
        print 'We got a timeout ... Sleeping for 15 minutes'

该异常未按您认为的那样使用。如果您正在编写的代码中存在错误,则会引发异常,不是您从 Twitter 获得的 错误。