2014-06-10 95 views
1

最近我一直在玩tweepy,我試圖拉動追隨者和給定用戶的關注。tweepy中的循環錯誤

followingids = [] 
followids = [] 
userid = "Someone"#sets target 

for page in tweepy.Cursor(api.followers_ids, screen_name=userid).pages():#gets the followers for userID 
    followingids.extend(page) 
    time.sleep(60)#keeps us cool with twitter 


    for page in tweepy.Cursor(api.friends_ids, screen_name=userid).pages():#gets the followers for userID 
    followids.extend(page) 
    time.sleep(60)#keeps us cool with twitter 

#where weirdness starts 
print len(followingids), "followers have been gathered from", userid 
print len(followids), " users are followed by ", userid 

followingusers = api.lookup_users(user_ids=followingids)#ieterates through the list of users and prints them 
followedusers = api.lookup_users(user_ids=followids) #<does not work but above does 


print "users of following", userid 
for u in followingusers: 
    print u.screen_name 


print "users followed by", userid 
for s in followedusers: 
    print s.screen_name 

for循環的第二打印給出了這樣的錯誤:

Traceback (most recent call last): 
    File "twitterBot.py", line 30, in <module> 
    followedusers = api.lookup_users(user_ids=followids) #<does not work but above does 
    File "/usr/local/lib/python2.7/dist-packages/tweepy/api.py", line 160, in lookup_users 
    return self._lookup_users(list_to_csv(user_ids), list_to_csv(screen_names)) 
    File "/usr/local/lib/python2.7/dist-packages/tweepy/binder.py", line 230, in _call 
    return method.execute() 
    File "/usr/local/lib/python2.7/dist-packages/tweepy/binder.py", line 203, in execute 
    raise TweepError(error_msg, resp) 
tweepy.error.TweepError: [{u'message': u'Too many terms specified in query.', u'code': 18}] 

兩個followedusers和關注擁有Twitter ID號,我從字面上剪切和粘貼代碼打印那麼,爲什麼第一個工作和第二個不行?

+0

你可以顯示生成下面的代碼和followids的代碼嗎? –

+0

已添加,但代碼正常工作,因爲它應該將ID加載到列表中。 –

回答

6

您的代碼沒有被破壞,必然。使用GET用戶查找的Twitter limits you to returning 100 users(這是api.lookup_users所做的)。請求超過100將導致Tweepy錯誤代碼18,您只能獲得跟隨用戶的查詢,這看起來像您查詢的用戶跟隨超過100個用戶,但後面是少於100.

一個簡單的解決方案將是通過追隨者/關注用戶列表來迭代搜索(如果希望代碼更健壯,則兩者都是安全的)。遍歷每100個用戶標識並使用api.lookup_users一次只能查找最多100個用戶標識。