我是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
答案 0 :(得分:1)
如果你没有从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'
没有使用您认为的异常。如果您正在编写的代码中出现错误,则会引发异常, not 您从twitter获得的错误。
答案 1 :(得分:0)
看起来像这一行
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