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

来源:互联网 发布:欧姬丝洗发水 知乎 编辑:程序博客网 时间:2024/06/16 23:04

实用代码片段


简介

下面是一些在使用Tweepy或许对你有用的代码片段。


OAuth

auth = tweepy.OAuthHandler("consumer_key", "consumer_secret")# Redirect user to Twitter to authorizeredirect_user(auth.get_authorization_url())# Get access tokenauth.get_access_token("verifier_value")# Construct the API instanceapi = tweepy.API(auth)

分页/编页码

# Iterate through all of the authenticated user's friendsfor friend in tweepy.Cursor(api.friends).items():    # Process the friend here    process_friend(friend)# Iterate through the first 200 statuses in the friends timelinefor 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
原创粉丝点击