如何让代码识别Instagram个人主页的“页面不可用”状态?
解决Instagram用户名不存在时的页面识别问题
Instagram的“页面不可用”页面仍返回200状态码,导致仅靠状态码无法区分有效页面和无效页面,以下是可行的解决方法:
方法一:检查页面特征文本
无效页面会显示固定的提示文本(多语言版本对应不同内容),请求页面后直接查找该文本即可判断:
import requests def get_valid_instagram_profile(profile_url): # 添加请求头避免被反爬 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(profile_url, headers=headers) if response.status_code != 200: return None # 检查多语言下的页面不可用提示 invalid_texts = [ "Sorry, this page isn't available.", "抱歉,此页面不可用。", "Lo sentimos, esta página no está disponible." ] for text in invalid_texts: if text in response.text: return None return profile_url
方法二:解析页面内嵌的共享数据
Instagram页面会嵌入window._sharedData JSON对象,有效个人主页会包含ProfilePage入口,无效页面则没有,这种方法比文本匹配更可靠:
import requests import re import json def get_valid_instagram_profile(profile_url): 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(profile_url, headers=headers) if response.status_code != 200: return None # 提取内嵌的共享数据 data_match = re.search(r'window\._sharedData = (.*?);', response.text) if not data_match: return None try: shared_data = json.loads(data_match.group(1)) # 判断是否存在有效个人主页数据 if 'entry_data' in shared_data and 'ProfilePage' in shared_data['entry_data']: return profile_url else: return None except json.JSONDecodeError: return None
注意事项
- Instagram有反爬机制,频繁请求可能被限制,建议添加请求头、控制请求频率,必要时使用代理IP。
- 页面结构可能随Instagram更新变化,若某方法失效,需重新观察页面特征调整代码。
内容的提问来源于stack exchange,提问作者nikitushu2
相关产品推荐
相关产品推荐

