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

Selenium使用Chrome无头驱动登录Outlook邮箱页面卡住问题求助

解决方案

该问题是Outlook登录页面的自动化检测机制导致的:页面会识别浏览器是否处于无头模式、窗口最小化等非常规操作状态,一旦判定为自动化工具访问,就会阻断流程触发页面冻结。可通过以下修改解决:

1. 为Chrome驱动添加反检测配置

添加启动参数移除自动化标识,绕过站点检测,无头模式下的配置示例如下:

o_options = Options()
# 使用Chrome新版无头模式,兼容性远高于旧版headless=True
o_options.add_argument("--headless=new")
# 模拟最大化窗口,避免窗口尺寸异常被识别
o_options.add_argument("--start-maximized")
# 移除浏览器的自动化控制标记
o_options.add_argument("--disable-blink-features=AutomationControlled")
o_options.add_experimental_option("excludeSwitches", ["enable-automation"])
o_options.add_experimental_option("useAutomationExtension", False)
# 替换为真实浏览器的User-Agent,避免无头模式默认UA被拦截
o_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")

o_driver = webdriver.Chrome(options=o_options, executable_path=r'你的Chrome驱动本地路径')
# 注入js代码隐藏navigator.webdriver属性,进一步绕过检测
o_driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
    "source": "Object.defineProperty(navigator, 'webdriver', {get: () => undefined})"
})

2. 优化元素等待逻辑

原有代码使用presence_of_element_located仅判断元素是否存在,未校验元素是否可交互,容易出现点击无效的问题,替换为element_to_be_clickable:

# 用户名输入&下一步点击
WebDriverWait(o_driver, 10).until(EC.element_to_be_clickable((By.ID, 'i0116'))).send_keys(o_username)
time.sleep(0.5)
WebDriverWait(o_driver, 10,(NoSuchElementException,StaleElementReferenceException,)).until(EC.element_to_be_clickable((By.ID, 'idSIButton9'))).click()

time.sleep(3)

# 密码输入&下一步点击
WebDriverWait(o_driver, 10).until(EC.element_to_be_clickable((By.ID, 'i0118'))).send_keys(o_password)
time.sleep(0.5)
WebDriverWait(o_driver, 10, (NoSuchElementException,StaleElementReferenceException,)).until(EC.element_to_be_clickable((By.ID, 'idSIButton9'))).click()

3. 最小化模式适配

如果不想用无头模式,一定要用最小化窗口,不要在初始化时就最小化,等登录流程完全走完进入收件箱后再执行最小化操作:

# 初始化先最大化窗口,保证登录流程正常
o_driver = webdriver.Chrome(r'你的Chrome驱动本地路径')
o_driver.maximize_window()

# 原有登录逻辑不变,直到检测到收件箱元素后再最小化
WebDriverWait(o_driver, 5).until(EC.presence_of_element_located((By.ID, 'Pivot29-Tab0')))
o_driver.minimize_window()

另外注意你现有代码中o_password的占位符写错成了用户名的提示,实际运行时要替换为正确的Outlook登录密码。如果你的账号开启了二次验证,还需要额外补充验证码/短信验证的处理逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 21:06:02