如何通过API获取关注列表并筛选取消关注数多于粉丝数的用户?
Hey there! Your plan to trim your following list while minimizing fan loss makes total sense—targeting users with more followings than followers is a smart strategy. Let’s walk through how to turn this into working code, step by step.
First, you need to pick the platform (I’m assuming it’s something like Twitter/X, Instagram, or similar) and dive into its official API docs:
- Authentication: Most platforms require OAuth2 credentials (API key, API secret, access token, access token secret) to access user-specific data like your following list or modify follow status. You’ll need to create a developer account on the platform to get these.
- Rate Limits: Every API has strict rate limits to prevent abuse. For example, Twitter’s v2 API lets you fetch up to 900 user details every 15 minutes. Ignoring these will get your access temporarily blocked.
- Endpoint Docs: Note the exact endpoints for:
- Fetching your list of followed users
- Fetching a user’s follower/following counts
- Unfollowing a user
Python is a great choice for this—it’s easy to write, has robust HTTP libraries, and handles pagination/rate limiting smoothly. Here’s what you’ll need:
- Install the
requestslibrary (for making API calls) withpip install requests - Store your API credentials securely (don’t hardcode them! Use environment variables or a
.envfile withpython-dotenv)
Let’s break down each part with example code (using Twitter/X v2 API as a reference—adjust endpoints for your platform):
3.1 Fetch All Followed Users
Most APIs paginate results (you can’t get all 1800 users in one call). You’ll need to loop through pages using a pagination token:
import requests import os from dotenv import load_dotenv load_dotenv() BEARER_TOKEN = os.getenv("BEARER_TOKEN") USER_ID = os.getenv("USER_ID") def get_following_list(): following = [] url = f"https://api.twitter.com/2/users/{USER_ID}/following" params = {"max_results": 1000, "user.fields": "id"} while True: response = requests.get(url, headers={"Authorization": f"Bearer {BEARER_TOKEN}"}, params=params) response.raise_for_status() data = response.json() following.extend([user["id"] for user in data.get("data", [])]) # Check if there's a next page next_token = data.get("meta", {}).get("next_token") if not next_token: break params["pagination_token"] = next_token return following following_users = get_following_list() print(f"Fetched {len(following_users)} followed users")
3.2 Fetch Follower/Following Counts for Each User
Loop through your following list, fetch each user’s metrics, and track who meets your criteria:
import time def get_user_metrics(user_id): url = f"https://api.twitter.com/2/users/{user_id}" params = {"user.fields": "public_metrics"} response = requests.get(url, headers={"Authorization": f"Bearer {BEARER_TOKEN}"}) response.raise_for_status() data = response.json()["data"] return { "id": user_id, "followers_count": data["public_metrics"]["followers_count"], "following_count": data["public_metrics"]["following_count"] } # Filter users where following > followers unfollow_candidates = [] for user_id in following_users: try: metrics = get_user_metrics(user_id) if metrics["following_count"] > metrics["followers_count"]: unfollow_candidates.append(user_id) # Add a small delay to avoid hitting rate limits time.sleep(1) except Exception as e: print(f"Failed to fetch metrics for {user_id}: {e}") print(f"Found {len(unfollow_candidates)} users to unfollow")
3.3 Batch Unfollow Target Users
Again, respect rate limits and avoid rapid-fire requests. Add delays between each unfollow:
def unfollow_user(target_user_id): url = f"https://api.twitter.com/2/users/{USER_ID}/following/{target_user_id}" response = requests.delete(url, headers={"Authorization": f"Bearer {BEARER_TOKEN}"}) response.raise_for_status() return response.json() # Unfollow in batches (e.g., 10 users at a time with a longer delay between batches) batch_size = 10 for i in range(0, len(unfollow_candidates), batch_size): batch = unfollow_candidates[i:i+batch_size] for user_id in batch: try: unfollow_user(user_id) print(f"Unfollowed {user_id}") time.sleep(2) except Exception as e: print(f"Failed to unfollow {user_id}: {e}") # Wait 5 minutes between batches to be safe time.sleep(300)
- Test First: Run the code with a small subset of users (e.g., pick 10 users from your following list) to verify your filtering logic works before unfollowing hundreds.
- Backup Your List: Export your full following list first (using the
get_following_listfunction) so you can restore if you make a mistake. - Don’t Rush: Platforms flag rapid mass unfollows as spam. Slow down—even if it takes a few days to hit your 1000 target, it’s better than getting your account restricted.
- Check for Edge Cases: Some users might have private profiles (their follower count might not be visible via API). Add logic to skip these if needed.
内容的提问来源于stack exchange,提问作者shackles

