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

如何通过网页抓取检测Instagram账号私密/公开状态?适配无头模式

判断Instagram账号私密/公开状态(无头模式)

问题根源

Instagram页面内容依赖JavaScript动态渲染,直接用BeautifulSoup爬取的静态HTML源码里不会包含账号私密状态的标识信息,必须等待页面完全加载、JS执行完成后才能获取到相关元素。

解决方案:使用Selenium无头浏览器

通过Selenium启动无头模式的Chrome浏览器,模拟真实用户访问页面,等待动态内容渲染完成后,查找页面中的私密状态标识元素。

步骤1:安装依赖

pip install selenium

同时需要下载与本地Chrome版本匹配的ChromeDriver,可将其配置到系统环境变量中,或在代码里直接指定文件路径。

步骤2:代码实现

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

def check_instagram_private(username):
    # 配置无头Chrome选项
    chrome_options = Options()
    chrome_options.add_argument("--headless=new")
    chrome_options.add_argument("--disable-gpu")
    chrome_options.add_argument("--no-sandbox")
    chrome_options.add_argument("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")

    # 初始化浏览器
    driver = webdriver.Chrome(options=chrome_options)
    url = f"https://www.instagram.com/{username}/"
    
    try:
        driver.get(url)
        # 等待页面核心元素加载,最多等待10秒
        WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.TAG_NAME, "body"))
        )
        
        # 判断私密账号标识:查找包含"This Account is Private"的元素
        private_indicator = driver.find_elements(By.XPATH, "//h2[contains(text(), 'This Account is Private')]")
        if private_indicator:
            return True  # 账号为私密
        else:
            # 验证用户名是否有效
            not_found = driver.find_elements(By.XPATH, "//h2[contains(text(), 'Sorry, this page isn\\'t available.')]")
            if not_found:
                raise ValueError(f"用户名 {username} 不存在")
            return False  # 账号为公开
    finally:
        driver.quit()

# 测试示例
if __name__ == "__main__":
    target_username = "test_user"
    try:
        is_private = check_instagram_private(target_username)
        print(f"账号 {target_username} 是{'私密' if is_private else '公开'}状态")
    except ValueError as e:
        print(e)

关键说明

  • 无头模式适配:通过--headless=new启用新版无头模式,完全适配后端无GUI运行环境。
  • 反爬规避:设置真实用户代理,降低被Instagram识别为爬虫的概率。
  • 状态判断逻辑:私密账号会显示固定提示文本,公开账号无该元素;同时增加用户名有效性校验,避免误判。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 15:22:32