首页 > 解决方案 > 如何使用 Tweepy 和 Python 取消关注 5 个用户

问题描述

我想运行一个使用 Tweepy 和 Python 一次只取消关注 5 个用户的脚本。以下脚本有效,但在我取消关注 5 个用户后它继续运行。如何让它在 5 点停止?谢谢你的帮助!

import tweepy
import time

def get_twitter_api():
    # personal details
    consumer_key = "xxxx"
    consumer_secret = "xxxx"
    access_token = "xxxx"
    access_token_secret = "xxxx"

    # authentication of consumer key and secret
    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)

    # authentication of access token and secret
    auth.set_access_token(access_token, access_token_secret)
    api = tweepy.API(auth, wait_on_rate_limit=True)
    return api

def process():
    interval = 61
    api = get_twitter_api()

    followers = api.followers_ids(api.me().id)
    print("Followers", len(followers))
    friends = api.friends_ids(api.me().id)
    print("You follow:", len(friends))


    for friend in friends[::-1]:
        if friend not in followers:
            api.destroy_friendship(friend) 
            time.sleep(interval)
            amount = 5

if __name__ == "__main__":
    process()

标签: pythontweepy

解决方案


您可以在循环0之前设置一个变量。然后,您可以在语句 中增加变量 by 。 然后你可以在之后添加另一个语句,检查变量是否等于,如果是,或者。for
1if
if5breakreturn

例如:

    amount = 0

    for friend in friends[::-1]:
        if friend not in followers:
            api.destroy_friendship(friend) 
            time.sleep(interval)

            amount += 1

            if amount == 5:
                break

您可能希望sleep在增量之前检查,如果您不希望它在最后一个之后等待。


推荐阅读