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

使用Selenium detach属性后浏览器仍自动关闭的问题求助

解决Selenium Chrome浏览器自动关闭的问题

问题根源分析

  • detach选项未生效的核心原因:你在初始化webdriver.Chrome实例之后才创建并配置chrome_options,导致配置完全没有被应用到浏览器实例上。必须在创建浏览器对象时,把预先配置好的Options传进去。
  • implicit_wait的误用:browser.implicitly_wait(20000)的参数是秒数而非毫秒,且这个方法仅用于设置元素查找的隐式等待超时,和阻止浏览器关闭没有任何关系。

修正后的完整代码

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from webdriver_manager.chrome import ChromeDriverManager

# 先配置Chrome选项,添加detach参数
chrome_options = Options()
chrome_options.add_experimental_option("detach", True)

s = Service(ChromeDriverManager().install())
# 创建浏览器实例时传入配置好的chrome_options
browser = webdriver.Chrome(service=s, options=chrome_options)
browser.maximize_window()

browser.get("https://rahulshettyacademy.com")
print(browser.title)
browser.get("https://rahulshettyacademy.com/angularpractice/")
print(browser.title)

browser.find_element(By.XPATH,"//body/app-root[1]/form-comp[1]/div[1]/form[1]/div[1]/input[1]").send_keys("OVM")
browser.find_element(By.XPATH,"//body/app-root[1]/form-comp[1]/div[1]/form[1]/div[2]/input[1]").send_keys("ovm@gmail.com")
browser.find_element(By.ID,"exampleInputPassword1").send_keys("123456789")
browser.find_element(By.XPATH,"//input[@id='exampleCheck1']").click()
browser.find_element(By.XPATH,"//select[@id='exampleFormControlSelect1']").click()
browser.find_element(By.XPATH,"//input[@id='inlineRadio2']").click()
browser.find_element(By.XPATH,"//body/app-root[1]/form-comp[1]/div[1]/form[1]/div[7]/input[1]").send_keys("01/01/2000")

# 若需脚本执行后暂停一段时间,可使用time.sleep(示例:暂停10秒)
# import time
# time.sleep(10)

补充说明

  • 确保detach选项在创建webdriver.Chrome实例前配置完成,并通过options参数传入,这样脚本执行完毕后浏览器会保持打开状态。
  • 如果需要在脚本执行过程中暂停,使用time.sleep(秒数)即可,不要混淆它和implicit_wait的作用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 15:50:26