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

如何使用Selenium仅登录一次即可批量截图Instagram账号?

解决方案

问题根源

你的代码存在几个核心问题导致无法正常截图:

  • 循环内重复创建多个浏览器实例,登录后关闭了带登录状态的browser,但截图用的driver是全新未登录的实例,自然会跳转到登录界面
  • 未处理登录后的弹窗(如"保存登录信息""开启通知"),可能阻塞后续页面访问
  • 无头模式未配置user-agent,容易被Instagram的反爬机制检测到,强制要求验证

修正后的代码

import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from credentials import userName, password

# 目标账号列表
target_accounts = ["duolingo", 'duolingobrasil', 'duolingodeutschland', 'duolingofrance', 'duolingespanol']

# 配置浏览器选项
chrome_options = Options()
chrome_options.add_argument('--headless=new')  # 新版无头模式,更接近真实浏览器
chrome_options.add_argument("--window-size=1920x1080")
# 添加user-agent,避免被反爬检测
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")
# 禁用图片加载,提升速度(可选)
chrome_options.add_argument("--blink-settings=imagesEnabled=false")

# 初始化单个浏览器实例
driver = webdriver.Chrome(options=chrome_options)
driver.implicitly_wait(10)  # 全局隐式等待

try:
    # 执行一次登录操作
    driver.get('https://www.instagram.com/accounts/login/')
    time.sleep(2)

    # 输入账号密码
    username_input = driver.find_element(By.CSS_SELECTOR, "input[name='username']")
    password_input = driver.find_element(By.CSS_SELECTOR, "input[name='password']")
    username_input.send_keys(userName)
    password_input.send_keys(password)

    # 点击登录按钮
    login_button = driver.find_element(By.XPATH, "//button[@type='submit']")
    login_button.click()
    time.sleep(5)

    # 处理登录后的弹窗:保存登录信息 - 选择"以后再说"
    try:
        not_now_btn = driver.find_element(By.XPATH, "//div[text()='以后再说']")
        not_now_btn.click()
        time.sleep(2)
    except:
        pass  # 如果没出现弹窗,跳过

    # 处理通知权限弹窗 - 选择"不允许"
    try:
        not_allow_btn = driver.find_element(By.XPATH, "//button[text()='不允许']")
        not_allow_btn.click()
        time.sleep(2)
    except:
        pass

    # 循环遍历每个账号,截图保存
    for idx, account in enumerate(target_accounts, start=1):
        driver.get(f"https://www.instagram.com/{account}/")
        time.sleep(5)  # 等待页面加载完成(可根据实际情况调整)
        # 截图保存,路径确保存在
        driver.save_screenshot(f'Pictures/duolingo_{idx}.png')
        print(f"已完成 {account} 的截图")

finally:
    # 无论成功失败,最后关闭浏览器
    driver.quit()

关键修改说明

  • 只初始化一个浏览器实例,全程复用登录状态
  • 配置了合理的user-agent和新版无头模式,降低被检测概率
  • 添加了登录后弹窗的处理逻辑,避免操作阻塞
  • 使用enumerate简化索引计数,代码更简洁
  • 用try-finally确保浏览器最终会关闭,避免资源泄漏

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 01:20:37