Python – Tweepy 中的 API.friends()
Twitter是一个流行的社交网络,用户在其中分享称为推文的消息。 Twitter 允许我们使用 Twitter API 或Tweepy挖掘任何用户的数据。数据将是从用户那里提取的推文。首先要做的是从 twitter 开发人员那里轻松获得每个用户可用的消费者密钥、消费者密钥、访问密钥和访问密钥。这些密钥将帮助 API 进行身份验证。
API.friends()
Tweepy 模块中API
类的friends()
方法用于获取指定用户的好友(他们关注的用户)在其中添加的顺序。
Syntax : API.friends(id / user_id / screen_name)
Parameters : Only use one of the 3 options:
id : specifies the ID or the screen name of the user
user_id : specifies the ID of the user, useful to differentiate accounts when a valid user ID is also a valid screen name
screen_name : specifies the screen name of the user, useful to differentiate accounts when a valid screen name is also a user ID
If no user is specified it defaults to the authenticated user.
Returns : a list of objects of the class User
示例 1: friends() 方法返回 20 个最近的朋友。
# 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)
输出 :
misskaul
rajyasabhatv
DDNewslive
TwitterMedia
abpmajhatv
htTweets
News18Haryana
jack
BBCHindi
the_hindu
mentalhealthind
ProKabaddi
firstpost
livemint
hcmariwala
mathrubhumi
PTUshaOfficial
anubhabhonsle
kmmalleswari
DipaKarmakar
示例 2:使用Cursor()
方法可以访问超过 20 个朋友。
# the screen_name of the targeted user
screen_name = "TwitterIndia"
# getting only 30 friends
for friend in tweepy.Cursor(api.friends, screen_name).items(30):
print(friend.screen_name)
输出 :
misskaul
rajyasabhatv
DDNewslive
TwitterMedia
abpmajhatv
htTweets
News18Haryana
jack
BBCHindi
the_hindu
mentalhealthind
ProKabaddi
firstpost
livemint
hcmariwala
mathrubhumi
PTUshaOfficial
anubhabhonsle
kmmalleswari
DipaKarmakar
NewIndianXpress
M_Raj03
DDNational
isro
PTTVOnlineNews
cricketnext
thebetterindia
AGSawant
MahendraP_BJP
DrRPNishank
示例 3:计算关注者的数量。
# the screen_name of the targeted user
screen_name = "geeksforgeeks"
# getting all the friends
c = tweepy.Cursor(api.friends, screen_name)
# counting the number of friends
count = 0
for friends in c.items():
count += 1
print(screen_name + " has " + str(count) + " friends.")
输出 :
geeksforgeeks has 8 friends.
在评论中写代码?请使用 ide.geeksforgeeks.org,生成链接并在此处分享链接。