在开发Instagram相关的数据采集、账号监测类程序时,准确识别个人资料页的“页面不可用”状态是核心需求之一,该状态可能对应账号封禁、内容删除、隐私限制等多种场景,不同场景的页面表现存在差异,需要结合多维度特征进行判断。

常见页面不可用场景及特征
首先需要明确不同不可用场景的典型表现,才能针对性设计识别逻辑,常见场景包括:
- 账号被封禁:页面会显示明确的封禁提示文案
- 账号不存在:返回404状态码,页面提示用户不存在
- 账号设为私密:需要登录才能查看内容,未登录访问会返回特定提示
- 内容被删除:原资料页链接失效,返回通用错误提示
基于HTTP响应状态码的初步判断
最基础的识别方式是通过请求返回的状态码做初步筛选,不同状态码对应不同的页面状态:
import requests
def check_instagram_profile_status(profile_url):
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
}
try:
response = requests.get(profile_url, headers=headers, timeout=10)
# 返回404说明账号不存在
if response.status_code == 404:
return "页面不可用:账号不存在"
# 返回403可能是权限不足或账号被限制访问
if response.status_code == 403:
return "页面不可用:访问权限不足"
# 返回200需要进一步解析页面内容
if response.status_code == 200:
return parse_profile_content(response.text)
return f"页面不可用:未知状态码{response.status_code}"
except requests.exceptions.RequestException as e:
return f"请求异常:{str(e)}"
# 测试示例
profile_url = "https://www.instagram.com/example_user/"
print(check_instagram_profile_status(profile_url))
解析页面内容识别具体不可用类型
当请求返回200状态码时,需要解析页面HTML内容判断具体状态,Instagram的页面不可用提示通常有固定的文案和结构特征:
from bs4 import BeautifulSoup
def parse_profile_content(page_html):
soup = BeautifulSoup(page_html, "html.parser")
# 提取页面中的提示文案,通常在特定的div标签中
error_tips = soup.find_all("div", class_="error-container")
if error_tips:
tip_text = error_tips[0].get_text(strip=True)
# 匹配封禁相关关键词
if "封禁" in tip_text or "banned" in tip_text.lower():
return "页面不可用:账号已被封禁"
# 匹配用户不存在关键词
if "用户不存在" in tip_text or "user not found" in tip_text.lower():
return "页面不可用:账号不存在"
# 匹配私密账号关键词
if "私密账号" in tip_text or "private account" in tip_text.lower():
return "页面不可用:账号设为私密"
# 检查页面是否包含正常的用户资料结构,比如用户名、头像区域
user_info = soup.find("section", class_="user-profile")
if not user_info:
return "页面不可用:未检测到有效用户资料结构"
return "页面可用:正常个人资料页"
结合API响应特征优化识别逻辑
如果程序是通过Instagram的官方API或第三方接口获取数据,还可以结合接口返回的结构化数据判断状态,比解析HTML更高效准确:
import json
def check_profile_by_api(api_response):
# 假设api_response是接口返回的JSON字符串
try:
data = json.loads(api_response)
# 接口返回错误码的情况
if "error" in data:
error_msg = data["error"].get("message", "")
if "user not found" in error_msg.lower():
return "页面不可用:账号不存在"
if "account banned" in error_msg.lower():
return "页面不可用:账号已被封禁"
return f"页面不可用:接口返回错误{error_msg}"
# 检查返回数据中是否包含用户核心信息
if "username" not in data or "id" not in data:
return "页面不可用:未返回有效用户数据"
return "页面可用:正常个人资料数据"
except json.JSONDecodeError:
return "页面不可用:接口返回数据格式错误"
注意事项
在实际开发中还需要注意以下几点:
- Instagram的页面结构和文案可能会更新,需要定期维护识别关键词和标签特征
- 频繁请求可能会触发反爬机制,导致返回的状态码和内容不准确,需要合理控制请求频率
- 不同地区的页面提示文案可能存在差异,建议同时匹配中英文关键词提升识别准确率
- 如果需要识别登录状态下的页面状态,需要在请求中携带有效的登录凭证