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

如何使用Selenium 4.14.0实现Instagram自动登录?

Instagram 自动登录代码方案(适配Selenium 4.14.0+Firefox 119.0+GeckoDriver 0.33.0)

前置准备

  1. 安装指定版本的Selenium库:
    pip install selenium==4.14.0
    
  2. 确认GeckoDriver已配置到系统环境变量,或准备好其绝对路径用于代码中指定。

完整代码示例

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException

# 配置Firefox浏览器选项
options = webdriver.FirefoxOptions()
# 可选:禁用浏览器通知,减少弹窗干扰
options.add_argument("--disable-notifications")

# 初始化浏览器(若GeckoDriver未在环境变量,需指定executable_path参数,如executable_path="/usr/local/bin/geckodriver")
driver = webdriver.Firefox(options=options)
driver.maximize_window()

try:
    # 打开Instagram登录页面
    driver.get("https://www.instagram.com/accounts/login/")

    # 等待用户名输入框加载并输入账号
    username_input = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.NAME, "username"))
    )
    username_input.send_keys("你的Instagram用户名")

    # 等待密码输入框加载并输入密码
    password_input = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.NAME, "password"))
    )
    password_input.send_keys("你的Instagram密码")

    # 点击登录按钮
    login_button = WebDriverWait(driver, 10).until(
        EC.element_to_be_clickable((By.XPATH, "//button[@type='submit']"))
    )
    login_button.click()

    # 处理"保存登录信息"弹窗(可选,根据页面实际显示调整)
    try:
        save_btn = WebDriverWait(driver, 5).until(
            EC.element_to_be_clickable((By.XPATH, "//div[text()='保存信息']"))
        )
        save_btn.click()
    except TimeoutException:
        pass

    # 处理"开启通知"弹窗(可选)
    try:
        skip_btn = WebDriverWait(driver, 5).until(
            EC.element_to_be_clickable((By.XPATH, "//button[text()='稍后再说']"))
        )
        skip_btn.click()
    except TimeoutException:
        pass

    print("登录成功")

except Exception as e:
    print(f"登录出错: {str(e)}")
finally:
    # 可选:注释掉driver.quit()可保持浏览器打开,方便调试
    # driver.quit()
    pass

重要提示

  • 用显式等待替代固定休眠时间,适配页面加载速度,提升代码稳定性。
  • 元素定位优先使用NAME属性,按钮用XPATH是因为部分按钮无唯一ID/NAME标识。
  • Instagram有反爬机制:不要频繁执行自动登录,建议用测试账号;可添加随机延迟(如time.sleep(random.uniform(1,3)))模拟人工操作,降低账号封禁风险。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 10:16:04