我正在尝试创建一个“简单”的脚本,该脚本将取消关注我所关注的用户,而不是使用Tweety模块为Python 3.5关注我。
import sys, time, tweepy
auth = tweepy.OAuthHandler('Consumer Key', 'Consumer Secret')
auth.set_access_token('Access Token', 'Access Token Secret')
api = tweepy.API(auth)
for page in tweepy.Cursor(api.friends, screen_name='My Twitter Handle').pages():
for friend in page:
relationship = api.show_friendship(source_screen_name='My Twitter Handle', target_screen_name=friend.screen_name)
print(relationship.followed_by)
time.sleep(13)
print('\nDone.')
sys.exit()
目前,上述代码的目的是简单地打印出不关注我的用户。代码执行时,Python会向我抛出:
AttributeError: 'tuple' object has no attribute 'followed_by'
我知道这不是真的,因为Twitter的文档提到它here。
但是,我不是专家,所以我在这里问这个问题。知道我做错了什么吗?
首先,如果您仔细阅读twitter文档,原始API将返回{target: .., source: ..}, not {followed_by: .., ..}
。
其次,您正在使用Tweepy,它是原始API的包装器。根据Tweepy doc,它返回一个friendship
对象(http://tweepy.readthedocs.org/en/v3.2.0/api.html#API.show_friendship)。但是,它没有解释我们如何使用这个对象。来源https://github.com/tweepy/tweepy/blob/master/tweepy/models.py#L237,它返回一个元组source, target
。 source
和target
都有followed_by
属性。我不确定你在寻找哪一个,但是你可以通过以下方式访问它们:
source, target = relationship
print(source.followed_by)
print(target.followed_by)
对于较新版本的Tweepy(3.5.0),show_friendship()
返回两个元素的元组,每个元素属于每个用户。例如:
result = api.show_friendship(A, B)
result
返回元组
(Friendship(blocked_by=False, muting=False,..., screen_name = A, ...), Friendship(blocked_by=False, muting=False,..., screen_name = B, ...)
然后,如果要访问属性followed_by
,请执行以下操作:
result[0].followed_by
您将获得您要求的属性。
实现目标的替代方法:
如果您需要这样做只是为了检查谁在关注您和谁不关注,一个简单的方法就是通过在您关注的人和跟随您的人之间获得设置差异。为此,您可以应用我在下面提供的代码:
import tweepy
Consumer Key = 'XXXXXXXXXXXX'
ConsumerSecret = 'XXXXXXXXXXXX'
AccessToken = 'XXXXXXXXXXXX'
AccessTokenSecret = 'XXXXXXXXXXXX'
#Keys for the program
auth = tweepy.OAuthHandler(ConsumerKey, ConsumerSecret)
auth.set_access_token(AccessToken, AccessTokenSecret)
#Inialize the API:
api = tweepy.API(auth)
#Get your followers and friends:
friendNames, followNames = [], []
for friend, follower in zip(tweepy.Cursor(api.friends).items(),
tweepy.Cursor(api.followers).items()):
friendNames.append(friend.name)
followNames.append(follower.name)
#Create sets to see who is not following you:
friendset = set(friendNames)
followset = set(followNames)
not_fback = friendset.difference(followset)
变量not_fback
将是一个集合,所有用户都没有关注你。
@ Jzbach的代码有一个错误,因为你不可能有相同数量的粉丝和朋友,因此必须分开。
使用此修补程序,脚本将提取正确的子集
#Get your followers and friends:
friendNames, followNames = [], []
for friend in tweepy.Cursor(api.friends).items():
friendNames.append(friend.screen_name)
for follower in tweepy.Cursor(api.followers).items():
followNames.append(follower.screen_name)
您可以更改以下代码。
而不是这个
print(relationship.followed_by)
使用这行代码:
print(relationship[0].followed_by)