【翻译】Tweepy 3.5.0 Doc (3) Code Snippets

实用代码片段


简介

下面是一些在使用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








  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值