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

Python Selenium代码未执行完毕,浏览器自动关闭问题求助

浏览器在Selenium执行输入操作前自动关闭的解决办法

我用Python和Selenium写了一段Web自动化代码,想打开谷歌页面并在搜索框输入"Test",但浏览器总是在输入操作完成前就自动关闭了,换Safari浏览器也有同样问题。代码如下:

from selenium import webdriver
from selenium.webdriver.common.by import By
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service

service = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=service)

driver.get("https://www.google.com/")
input = driver.find_element(By.XPATH, "//*[@id='APjFqb']")

input.send_keys("Test")

问题根源

Python脚本执行完所有代码后,Selenium的WebDriver实例会被自动回收,关联的浏览器进程也会随之关闭,所以还没看到输入完成,浏览器就提前关闭了。

解决方法

1. 添加暂停语句留住浏览器

在代码末尾加一行等待用户输入的代码,让程序保持运行状态,浏览器就不会自动关闭:

from selenium import webdriver
from selenium.webdriver.common.by import By
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service

service = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=service)

driver.get("https://www.google.com/")
# 避免用input当变量名,会覆盖Python内置函数
search_input = driver.find_element(By.XPATH, "//*[@id='APjFqb']")
search_input.send_keys("Test")

# 等待你按回车键再结束程序,浏览器会保持打开
input("按回车键关闭浏览器...")
# 手动关闭驱动(可选,程序结束也会自动关闭,但显式调用更规范)
driver.quit()

2. 用显式等待提升稳定性(推荐)

如果页面加载较慢,可能会出现还没找到输入框代码就执行完毕的情况,配合显式等待确保元素加载完成后再操作,同时保留暂停语句:

from selenium import webdriver
from selenium.webdriver.common.by import By
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

service = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=service)

driver.get("https://www.google.com/")
# 最多等待10秒,直到输入框出现
search_input = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.XPATH, "//*[@id='APjFqb']"))
)

search_input.send_keys("Test")

input("按回车键关闭浏览器...")
driver.quit()

3. 配置Chrome选项让浏览器保持打开

通过ChromeOptions设置detach参数,让浏览器在脚本结束后不自动关闭:

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

options = Options()
options.add_experimental_option("detach", True)

service = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=service, options=options)

driver.get("https://www.google.com/")
search_input = driver.find_element(By.XPATH, "//*[@id='APjFqb']")
search_input.send_keys("Test")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 07:05:29