Skip to main content
 首页 » 编程设计

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

2025年05月04日14unruledboy

我是 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 

请您参考如下方法:

如果您没有收到来自 python 的错误并且控制台只是“挂起”,那么您实际上确实连接到了 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 获得的错误。