使用 tweepy 获取指定用户在 Twitter 上的所有好友

11

使用 tweepy,我能够使用游标返回所有朋友。 是否可能指定另一个用户并获取他们的所有朋友?

user = api.get_user('myTwitter')
print "Retreiving friends for", user.screen_name
for friend in tweepy.Cursor(api.friends).items():
 print "\n", friend.screen_name

如何使用 tweepy 获取任何给定用户的朋友?如果我将第一行更改为另一个 Twitter 用户,它仍然会返回我的朋友列表。

#first line is changed to
user = api.get_user('otherUsername') #still returns my friends

此外,当打印user.screen_name时,将会返回otherUsername

问题使用Tweepy获取Twitter中的所有关注者ID基本上是我正在寻找的,但它只返回ID的数量。如果我删除len()函数,我可以遍历用户ID列表,但是否可能获得屏幕名称@twitter@stackoverflow@etc.....


可能是获取Twitter所有关注者ID的Tweepy问题的重复。 接受答案中的变量ids包含所有ID,答案者打印其长度,但您可以根据需要进行操作。 - Luigi
我并不认为这是重复的问题,我正在寻找Twitter的handles或者screen_name,而不是返回在该问题中的IDs。我将其包含在问题本身作为参考,因为我的代码基本上是相同的。 - user2497792
感谢您进行澄清编辑。 - Luigi
2个回答

17
你可以使用你在另一个答案中引用的答案中的ids变量来获取给定人员的所有关注者的id,并使用Tweepy的api.lookup_users方法扩展它以获取所有关注者的屏幕名称:
import time
import tweepy

auth = tweepy.OAuthHandler(..., ...)
auth.set_access_token(..., ...)

api = tweepy.API(auth)

ids = []
for page in tweepy.Cursor(api.followers_ids, screen_name="McDonalds").pages():
    ids.extend(page)
    time.sleep(60)

screen_names = [user.screen_name for user in api.lookup_users(user_ids=ids)]

3
这个解决方案做到了我想要的。 - user2497792
1
当我尝试这个时,我得到了这个错误,有人知道是否有什么变化吗?谢谢。 tweepy.error.TweepError: [{u'message': u'Too many terms specified in query.', u'code': 18}] - 10mjg
一次只能处理100个ID。 - brienna

0
你可以使用这个:
# import the module
import tweepy
  
# assign the values accordingly
consumer_key = ""
consumer_secret = ""
access_token = ""
access_token_secret = ""
  
# authorization of consumer key and consumer secret
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
  
# set access to user's access key and access secret 
auth.set_access_token(access_token, access_token_secret)
  
# calling the api 
api = tweepy.API(auth)
  
# the screen_name of the targeted user
screen_name = "TwitterIndia"
  
# printing the latest 20 friends of the user
for friend in api.friends(screen_name):
    print(friend.screen_name)

更多详情请参见https://www.geeksforgeeks.org/python-api-friends-in-tweepy/


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接