如何使用requests获取Instagram账号所有粉丝的粉丝数?
提取Instagram账号粉丝的粉丝数解决方案
需求说明
- 目标:获取指定Instagram账号所有粉丝各自的粉丝数,输出格式示例:
John 17 followers adam 120 followers will 172 followers
- 当前问题:用
requests直接请求主页HTML,无法提取到粉丝数据
问题原因
Instagram采用动态渲染技术,静态HTML里不包含真实的粉丝列表数据,而且直接爬取会触发反爬机制。必须通过官方API接口获取数据,且需要合法认证。
解决方案
1. 依赖官方API
必须使用Instagram官方提供的API(比如Basic Display API或Graph API),需要先注册开发者账号,创建应用并获取访问令牌。注意:
- 仅能获取公开账号的粉丝列表,私人账号的粉丝数据无法获取(除非你是账号持有者)。
- 需遵守API调用频率限制,避免账号被封禁。
2. 代码实现示例
import requests # 替换为你的有效访问令牌和目标账号的user_id ACCESS_TOKEN = "你的访问令牌" TARGET_USER_ID = "目标账号的user_id" # 获取目标账号的粉丝列表 def get_followers(user_id, access_token): followers = [] request_url = f"https://graph.instagram.com/{user_id}/followers?fields=username,id&access_token={access_token}" while request_url: resp = requests.get(request_url).json() if "data" in resp: followers.extend(resp["data"]) # 处理分页 request_url = resp.get("paging", {}).get("next") return followers # 获取单个用户的粉丝数 def get_follower_count(user_id, access_token): resp = requests.get(f"https://graph.instagram.com/{user_id}?fields=followers_count&access_token={access_token}").json() return resp.get("followers_count", 0) # 主逻辑 if __name__ == "__main__": all_followers = get_followers(TARGET_USER_ID, ACCESS_TOKEN) for follower in all_followers: name = follower["username"] count = get_follower_count(follower["id"], ACCESS_TOKEN) print(f"{name} {count} followers")
关键提示
- 如何获取
user_id:可以通过API接口https://graph.instagram.com/用户名?fields=id&access_token=你的令牌查询。 - 访问令牌需要具备
user_followers等相关权限,申请时需确认权限范围。
内容的提问来源于stack exchange,提问作者mcccc
相关产品推荐
相关产品推荐

