实用代码片段
简介
下面是一些在使用Tweepy或许对你有用的代码片段。
OAuth
auth = tweepy.OAuthHandler("consumer_key", "consumer_secret")
# Redirect user to Twitter to authorize
redirect_user(auth.get_authorization_url())
# Get access token
auth.get_access_token("verifier_value")
# Construct the API instance
api = tweepy.API(auth)
分页/编页码
# Iterate through all of the authenticated user's friends
for friend in tweepy.Cursor(api.friends).items():
# Process the friend here
process_friend(friend)
# Iterate through the first 200 statuses in the friends timeline
for status in tweepy.Cursor(api.friends_timeline).items(200):
# Process the status here
process_status(status)
FollowAll
这个片段会关注每一个授权用户的关注者。
for follower in tweepy.Cursor(api.followers).items():
follower.follow()
用 cursor 来处理 rate limit
由于 cursors 会在 next() 方法中抛出 RateLimitError,我们可以用将 cursor 包含在迭代器中的方法进行处理。
运行下面这段代码将打印出所有你所关注的人中,被他们关注的人小于300个的人。这样做是为了避免明显的机器人账号。而且这段代码还会在每次超过rate limit时等待15分钟。
# In this example, the handler is time.sleep(15 * 60),
# but you can of course handle it in any way you want.
def limit_handled(cursor):
while True:
try:
yield cursor.next()
except tweepy.RateLimitError:
time.sleep(15 * 60)
for follower in limit_handled(tweepy.Cursor(api.followers).items()):
if follower.friends_count < 300:
print follower.screen_name