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

如何使用Selenium with Python处理弹窗中的两个文本输入框?

处理HTTP基本认证弹窗的正确方法

你遇到的这个弹窗是HTTP Basic Authentication(HTTP基本认证),它不属于页面DOM元素,所以用Xpath定位或普通元素查找方法完全无效,这也是你之前尝试失败的核心原因。下面给你两种可行的解决方式:

方法一:直接在URL中嵌入用户名和密码(最简便)

HTTP基本认证支持直接将用户名和密码拼接在URL里访问,格式为https://[用户名]:[密码]@[网站地址]。修改代码中driver.get()的参数即可跳过认证弹窗:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time  # 补充导入time模块

options = webdriver.ChromeOptions()
options.add_experimental_option("detach", True)
driver = webdriver.Chrome(options=options)
driver.maximize_window()

# 直接在URL中加入用户名和密码
driver.get("https://admin:admin@the-internet.herokuapp.com/basic_auth")

time.sleep(2)
driver.quit()

方法二:使用Selenium的Alert类处理(部分浏览器支持)

部分浏览器允许将基本认证弹窗视为Alert对象,通过switch_to.alert来输入认证信息:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time

options = webdriver.ChromeOptions()
options.add_experimental_option("detach", True)
driver = webdriver.Chrome(options=options)
driver.maximize_window()
driver.get("https://the-internet.herokuapp.com/basic_auth")

# 等待认证弹窗出现并切换到弹窗
alert = WebDriverWait(driver, 10).until(EC.alert_is_present())
# 按"用户名:密码"的格式输入内容
alert.send_keys("admin:admin")
# 确认弹窗完成认证
alert.accept()

time.sleep(2)
driver.quit()

你原代码中的几个问题:

  • EC.presence_of_element_located()必须传入定位器参数(如(By.ID, "xxx")),但该弹窗元素不在页面DOM中,这种方法完全不适用。
  • Python中Selenium的输入方法是send_keys(),不是Java风格的sendKeys()。
  • 缺少import time语句,会导致time.sleep(2)报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 05:10:14