【问题标题】:Get all friends of a given user on twitter with tweepy使用 tweepy 在 Twitter 上获取给定用户的所有朋友
【发布时间】:2015-01-03 17:49: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

打印我所有朋友的列表,但是如果我更改第一行 对于另一个 twitter 用户,它仍然返回我的朋友。如何使用 tweepy 为任何给定用户交朋友?

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

另外user.screen_name 打印时返回otherUsername

Get All Follower IDs in Twitter by Tweepy 的问题基本上符合我的要求,但它只返回 ID 的计数。如果我删除 len() 函数,我将可以遍历用户 ID 列表,但是否可以获得屏幕名称 @twitter@stackoverflow@etc.....

【问题讨论】:

  • Get All Follower IDs in Twitter by Tweepy 的可能副本。接受的答案中的变量ids 包含所有ID,回答者打印它的长度,但你可以用它做任何你想做的事情。
  • 我不一定认为这是重复的问题,我正在寻找 twitter 句柄或screen_name,而不是问题中返回的 ID,我将其包含在问题本身中参考,因为我的代码本质上是一样的
  • 感谢您的澄清编辑。

标签: python twitter tweepy


【解决方案1】:

您可以使用您在另一个答案中引用的answer 中的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)]

【讨论】:

  • 这个解决方案符合我的要求。
  • 我在尝试此操作时收到此错误,有谁知道是否发生了变化?谢谢 tweepy.error.TweepError: [{u'message': u'Too many terms specified in query.', u'code': 18}]
  • 一次只需要100个id。
【解决方案2】:

你可以用这个:

# 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/

【讨论】:

    猜你喜欢
    • 2014-12-05
    • 2017-08-24
    • 1970-01-01
    • 1970-01-01
    • 2011-12-06
    • 1970-01-01
    • 2015-10-08
    • 2014-11-14
    • 1970-01-01
    相关资源
    最近更新 更多