PyCharm运行Selenium代码时浏览器自动关闭,进程退出码为0如何解决?
Selenium自动化脚本浏览器自动关闭解决方案
问题根因与修复方案
- 默认执行完自动销毁机制:Selenium 4及以上版本默认在脚本所有代码执行完毕后自动销毁WebDriver实例,同步关闭关联浏览器。修复方式为在Chrome配置中添加保持进程存活的参数:
options.add_experimental_option("detach", True)
- API传参不兼容触发异常闪退:当前代码使用的
webdriver.Chrome(PATH, chrome_options=options)是Selenium 3的旧写法,Selenium 4已废弃chrome_options参数,且要求通过Service类传递chromedriver路径,错误传参会触发执行异常直接终止进程导致浏览器关闭。需调整初始化逻辑:
首先导入缺失的依赖:
from selenium import webdriver from selenium.webdriver.chrome.service import Service
修改WebDriver初始化代码:
service = Service(executable_path=PATH) driver = webdriver.Chrome(service=service, options=options)
- 依赖版本不匹配:需确保chromedriver的大版本和本地安装的Chrome浏览器大版本完全一致,版本差异会触发未知运行异常导致浏览器自动关闭。
- 路径转义或业务代码报错终止进程:Windows系统下文件路径的反斜杠会被识别为转义字符触发路径报错,表单提交逻辑执行异常也会直接终止脚本,可在代码末尾临时添加
input("按回车结束程序"),方便定位具体报错点。
修正后完整可运行代码
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.chrome.options import Options from selenium.webdriver.chrome.service import Service from fake_useragent import UserAgent options = Options() # 保持浏览器运行不自动关闭 options.add_experimental_option("detach", True) ua = UserAgent() user_agent = ua.random print(user_agent) options.add_argument(f"user-agent={user_agent}") # 路径前加r前缀避免转义字符报错 PATH = r"C:\Program Files (x86)\chromedriver.exe" service = Service(executable_path=PATH) driver = webdriver.Chrome(service=service, options=options) driver.get("my page") driver.find_element(By.ID, "form-email").send_keys("my e-mail") driver.find_element(By.ID, "form-password").send_keys("my password") driver.find_element(By.XPATH, "//button[@class='Wrapper-sc-8so8sv eyQKCA']").submit()
内容的提问来源于stack exchange,提问作者czopek123
相关产品推荐
相关产品推荐

