Python脚本检测Instagram用户隐私状态的替代方案咨询
获取Instagram用户公开/私密状态的替代方法
你提到的旧API端点已被Instagram废弃,无法正常返回数据。以下是两种可行的替代方案:
方案一:抓取网页端公开数据(无需登录)
直接请求用户的Instagram主页,解析页面内嵌的用户数据判断账号状态。该方法无需认证,适合检测公开/私密状态,但对私密账号仅能获取状态,无法查看内容。
import requests from bs4 import BeautifulSoup import json def check_instagram_private_status(username): url = f"https://www.instagram.com/{username}/" headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36" } response = requests.get(url, headers=headers) if response.status_code != 200: return None # 用户不存在或访问被限制 soup = BeautifulSoup(response.text, "html.parser") # 定位包含用户核心数据的脚本标签 shared_data_script = soup.find("script", string=lambda t: t and "window._sharedData" in t) if not shared_data_script: return None # 提取并解析JSON数据 data_json = shared_data_script.string.split("window._sharedData = ")[1].rstrip(";") data = json.loads(data_json) try: user_profile = data["entry_data"]["ProfilePage"][0]["graphql"]["user"] return user_profile["is_private"] except KeyError: return None # 使用示例 target_user = "test_user" status = check_instagram_private_status(target_user) if status is None: print("无法获取用户信息,请检查用户名或网络状态") elif status: print(f"@{target_user} 是私密账号") else: print(f"@{target_user} 是公开账号")
注意事项:
- Instagram会对频繁请求进行限制,建议添加请求间隔(如
time.sleep(2)),必要时使用代理IP; - 页面结构可能随Instagram更新变化,若解析失败需调整脚本定位逻辑。
方案二:使用官方Instagram Graph API(稳定可靠)
这是官方支持的途径,稳定性高但需完成开发者认证流程:
- 注册Facebook开发者账号并创建应用;
- 获取有效的访问令牌(需通过OAuth授权)。
通过API端点直接获取用户私密状态:
import requests def check_private_via_graph_api(username, access_token): api_url = f"https://graph.instagram.com/{username}?fields=is_private&access_token={access_token}" response = requests.get(api_url) if response.status_code == 200: return response.json().get("is_private") else: print(f"API请求失败:{response.text}") return None # 使用示例(替换为你的有效访问令牌) access_token = "YOUR_VALID_ACCESS_TOKEN" target_user = "test_user" status = check_private_via_graph_api(target_user, access_token) print(status)
优势:官方接口稳定性高,支持获取更多用户详情(需配置相应权限),适合长期运行的项目。
内容的提问来源于stack exchange,提问作者Ranjith N
相关产品推荐
相关产品推荐

