Tweepy:AttributeError:'tuple'对象没有属性'followed_by'

时间:2016-01-07 19:45:02

标签: python api twitter tweepy

我正在尝试创建一个“简单”脚本,该脚本将取消关注我正在关注的用户,而不是使用Python 3.5的Tweepy模块关注我。

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

但是,我不是专家,所以我在这里问这个问题。知道我做错了吗?

4 个答案:

答案 0 :(得分:1)

首先,如果您仔细阅读twitter文档,原始API将返回{target: .., source: ..}, not {followed_by: .., ..}

其次,您正在使用Tweepy,它是原始API的包装器。根据Tweepy文档,它返回一个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, targetsourcetarget都有followed_by个属性。我不确定你在寻找哪一个,但是你可以通过以下方式访问它们:

source, target = relationship
print(source.followed_by)
print(target.followed_by)

答案 1 :(得分:0)

直接回答您的疑问&实现目标的替代方法(下)

对于较新版本的 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将是一个包含所有未跟踪您的用户的集合。

答案 2 :(得分:0)

@ 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)

答案 3 :(得分:0)

您可以更改以下代码。

代替这个

print(relationship.followed_by)

使用以下代码行:

print(relationship[0].followed_by)