2016-10-01 53 views
0

我一直在尝试使用Tweepy或Twython与Twitter API来搜索特定的hashtag,提取用户使用hashtage进行推文的用户名,然后查看其中有多少人用户相互关注。我的最终目标是用NetworkX显示连接。Python:检查Twitter用户A以下用户B

到目前为止,我已经能够搜索哈希标签并获得用户的推特列表。但是,我无法弄清楚如何看清谁在谁的名单上。我终于找到了一个友情查找工作,但后来才意识到该参数只搜索经过身份验证的用户(我)的朋友。

这里是代码的最新版本:

from twython import Twython 
import tweepy 

# fill these in from Twitter API Dev 
CONSUMER_KEY = '' 
CONSUMER_SECRET = '' 
ACCESS_KEY = '' 
ACCESS_SECRET = '' 

auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) 
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET) 
api = tweepy.API(auth, wait_on_rate_limit=True) 

twitter = Twython(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_KEY, ACCESS_SECRET) 

# Search for hashtag, limit number of users 
try: 
    search_results = twitter.search(q='energy', count=5) 
except TwythonError as e: 
    print e 

test5 = [] 
for tweet in search_results['statuses']: 
    if tweet['user']['screen_name'] not in test5: 
     test5.append((tweet['user']['screen_name']).encode('utf-8')) 
print test5 

# Lookup friendships 
relationships = api.lookup_friendships(screen_names=test5[0:5]) 
for relationship in relationships: 
    if relationship.is_following: 
     print("User is following", relationship.screen_name) 

谢谢!

+0

我认为,对于每5000个名字的过度请求,您必须等待60秒才能提出下一个请求。 – thesonyman101

回答

1

使用Tweepy,您可以使用API.exists_friendship方法检查user_a后跟user_b。代码如下所示:

auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) 
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET) 
api = tweepy.API(auth, wait_on_rate_limit=True) 
is_following = api.exists_friendship(user_a, user_b) 

您可以通过id或screenname指定用户。

或者,您可以获取使用API.followers_ids方法追随者的整个列表:

auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) 
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET) 
api = tweepy.API(auth, wait_on_rate_limit=True) 
user_b_followers = api.followers_ids(user_b) 
is_following = user_a in user_b_followers 

这种做法会更有意义,为用户的大型网络。

请记住,对于任何一种方法,您只能看到经过身份验证的用户可以看到的友谊。这是Twitter为了保护隐私而制定的一项限制。

+0

嗨 - 非常感谢您的回复。但是,当前版本中exists_friendship参数不再存在,当我尝试followers_ids代码时,它出错并告诉我我无法做到这一点。你会有其他想法吗?谢谢。 –

+0

您是否尝试过[API.show_friendship](http://tweepy.readthedocs.io/en/v3.5.0/api.html#API.show_friendship)? – bslawski

相关问题