You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何利用Tweepy API获取指定Twitter账号的粉丝及该30位粉丝的粉丝

Solution to Fetch Followers of Followers with Tweepy

Looks like you're halfway there! Right now your code grabs the first 30 followers of a target account, but to get their followers, you just need to add a nested loop—think of it as digging one level deeper after you get the first set of results.

Step 1: Add a Nested Loop

After printing (or storing) each first-level follower, call api.followers again for that follower’s screen name. Here’s the adjusted code with error handling for edge cases:

import tweepy

# Make sure you've already authenticated your Tweepy API instance here
# Example auth setup:
# auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
# auth.set_access_token(access_token, access_token_secret)
# api = tweepy.API(auth, wait_on_rate_limit=True)

screen_name = input('Type the screen name: \n')

# First layer: Get 30 followers of the target account
for follower in tweepy.Cursor(api.followers, screen_name).items(30):
    first_level_handle = follower.screen_name
    print(f"\nFirst-level follower: *{first_level_handle}*")
    
    # Second layer: Fetch followers of this first-level user (limited to 10 to avoid rate limits)
    try:
        for second_level_follower in tweepy.Cursor(api.followers, first_level_handle).items(10):
            print(f"  Second-level follower: {second_level_follower.screen_name}")
    except tweepy.TweepError as e:
        print(f"  Could not get followers for {first_level_handle}: {e.reason}")

Key Things to Remember

  • Rate Limits: Twitter’s standard API allows 15 follower-fetch requests per 15-minute window. Enabling wait_on_rate_limit=True in your API setup will make Tweepy automatically pause when you hit limits instead of crashing.
  • Private Accounts: Some users have locked profiles—you can’t fetch their followers unless you’re approved to follow them. The try/except block catches these errors so your script keeps running.
  • Adjust Item Counts: I capped the second layer at 10 followers per user to avoid hitting rate limits quickly. You can tweak the items() value, but be cautious of how many requests you’re sending.

内容的提问来源于stack exchange,提问作者user81007

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 04:02:33