如何使用tweepy图书馆在Twitter上获得一个人的朋友和追随者?

2024-06-16 10:12:53 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我从(cursor2.items(100))中删除值100,下面的getting_friends_follwers()函数就会工作。我的目标是获取这些名字(追随者和朋友),并将它们保存在“amigos.txt”文件中

问题是screen_name这个名字有大量的朋友和追随者,因此Twitter关闭了这个连接。我曾想过尝试捕获100个名称中的100个(因此调用cursor2时的值为100),但出现了以下错误:

builtins.TypeError: '<' not supported between instances of 'User' and 'User'

如何修复它

Meu = []
def getting_friends_follwers():
    # Get list of followers and following for group of users tweepy
    f = open("amigos.txt","w")
    cursor = tweepy.Cursor(api.friends, screen_name="Carlos")
    cursor2 = tweepy.Cursor(api.followers, screen_name="Carlos")
##    for user in cursor.items():
##        print('friend: ' + user.screen_name)

    for user in sorted(cursor2.items(100)):###funciona se eu tirar este valor!!!
         f.write(str(user.screen_name)+ "\n")


         print('follower: ' + user.screen_name)

f.close()
getting_friends_follwers()

Tags: ofnamefor朋友items名字screenfriends
1条回答
网友
1楼 · 发布于 2024-06-16 10:12:53

您之所以会出现此错误,是因为您正在将项目传递给“排序”函数,该函数正在尝试对这些“用户”对象进行排序,但它无法做到这一点,因为没有关于如何“排序”两个用户对象的说明

如果删除“排序”,则程序将正常工作

此外,在调用函数之前,请关闭文件。我建议您使用“with open”语法来确保文件正确关闭

您可以这样编写代码:

def getting_friends_follwers(file):
    # Get list of followers and following for group of users tweepy
    cursor = tweepy.Cursor(api.friends, screen_name="Carlos")
    cursor2 = tweepy.Cursor(api.followers, screen_name="Carlos")
##    for user in cursor.items():
##        print('friend: ' + user.screen_name)

    for user in cursor2.items(100):###funciona se eu tirar este valor!!!
         file.write(str(user.screen_name)+ "\n")
         print('follower: ' + user.screen_name)

with open("amigos.txt", "w") as file:
    getting_friends_follwers(file)

相关问题 更多 >