我是Python的新手,但我正在尝试访问Twitter API,以获取Twitter手柄列表(或用户ID - 我有两个数据集)的关注者数量,并将它们打印到csv文件。我已经搜索了相当长的一段时间但没有发现任何真正有用的东西。
这就是我目前所拥有的:
import tweepy
import time
import csv
import sys
# Keys, tokens and secrets
consumer_key = 'REMOVED'
consumer_secret = 'REMOVED'
access_token = 'REMOVED'
access_token_secret = 'REMOVED'
# Tweepy OAuthHandler
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
targets = [12345,123456] # All your targets here
for target in targets:
user = api.get_user(target)
print(user.name, user.followers_count)
我的问题是:
我是否可以在预先填充的文件中包含所有目标,并在ID旁边的列中打印每个目标的跟随者数量?
如何添加count-break,因为:twitter API一次只能搜索100个用户... [所以]你需要做的是遍历每100个用户但是保持在速率限制范围内。
道歉,如果这是超级基础,并提前感谢任何帮助!
答案 0 :(得分:1)
总结评论中的讨论:
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import tweepy
import time
import unicodecsv as csv
import codecs
import sys
reload(sys)
sys.setdefaultencoding('utf8')
access_token = ''
access_token_secret = ''
consumer_key = ''
consumer_secret = ''
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth, wait_on_rate_limit=True)
with open('targets.txt', 'r') as targets_file:
targets_list = targets_file.readlines()
targets_list_filtered = filter(None, targets_list[0].split('\r'))
targets_list_cleaned = []
for item in targets_list_filtered:
targets_list_cleaned.append(item.strip('\n'))
with codecs.open('output.csv', 'wb', 'utf-8') as outcsv:
outfile = csv.DictWriter(outcsv, encoding='utf-8', fieldnames=['uID', 'Username', 'Follower Count', 'Verified'])
outfile.writeheader()
for idx, target in enumerate(targets_list_cleaned):
try:
user = api.get_user(target)
outfile.writerow({'uID': target, 'Username': user.name, 'Follower Count': user.followers_count, 'Verified': user.verified})
print idx, target, user.name, user.followers_count, user.verified
except tweepy.TweepError as e:
# outfile.writerow(e.message)
print idx, target, e.message
示例targets.txt
文件内容:
99795204
973058420
988290763
984965461
973058420
97074741
969892964
968396750