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

如何处理Python Selenium打开URL时弹出的身份认证窗口问题

问题原因

Chrome 81及以上版本出于安全策略限制,默认屏蔽了URL中携带用户名密码的Basic Auth认证逻辑,因此拼接认证信息到URL的方式已经失效,即使转义特殊字符也无法触发自动认证。

可行解决方案

方案1:Selenium 4+ 原生CDP接口实现(推荐,无额外依赖)

Selenium 4及以上版本原生支持Chrome DevTools Protocol(CDP),可以直接给请求注入认证头实现自动登录,代码如下:

import base64
from selenium import webdriver
from selenium.webdriver.chrome.service import Service

# 替换为实际信息
usrname = "你的用户名"
password = "你的密码"
MY_COLLEGE_URL = "目标站点域名及路径,不需要带https://前缀"

driver = webdriver.Chrome(service=Service("path/to/chromedriver.exe"))
# 启用网络域监听
driver.execute_cdp_cmd("Network.enable", {})
# 注入Basic Auth认证头
auth_token = base64.b64encode(f"{usrname}:{password}".encode()).decode()
driver.execute_cdp_cmd("Network.setExtraHTTPHeaders", {
    "headers": {
        "Authorization": f"Basic {auth_token}"
    }
})
# 直接访问目标地址即可完成自动认证
driver.get(f"https://{MY_COLLEGE_URL}")

方案2:使用selenium-wire第三方库处理

如果你的Selenium版本低于4,无法使用CDP接口,可以安装selenium-wire库实现认证:

  1. 先安装依赖:pip install selenium-wire
  2. 参考代码:
import base64
from seleniumwire import webdriver
from selenium.webdriver.chrome.service import Service

usrname = "你的用户名"
password = "你的密码"
MY_COLLEGE_URL = "目标站点域名及路径,不需要带https://前缀"

# 配置selenium-wire参数
wire_options = {
    "custom_authorization": f"Basic {base64.b64encode(f'{usrname}:{password}'.encode()).decode()}"
}
driver = webdriver.Chrome(
    service=Service("path/to/chromedriver.exe"),
    seleniumwire_options=wire_options
)
driver.get(f"https://{MY_COLLEGE_URL}")
注意事项
  • 用户名、密码中的特殊字符不需要手动转义,base64编码会自动处理
  • 请保证Chrome浏览器版本和chromedriver版本完全匹配,避免出现兼容性异常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 01:45:03