Selenium中executable_path弃用警告及页面加载后立即退出问题求助
解决方法
1. 消除DeprecationWarning警告
Selenium 4.x版本已弃用executable_path参数,需改用Service类指定驱动路径:
- 从
selenium.webdriver.chrome.service导入Service类 - 创建
Service实例传入驱动路径,再将其作为参数传给webdriver.Chrome()
2. 解决页面加载后自动退出问题
脚本执行完毕后Python进程终止,浏览器会随之关闭,有两种解决方式:
- 方式一:在代码末尾添加阻塞语句,等待用户输入后再关闭浏览器
- 方式二:配置ChromeOptions的
detach参数为True,让浏览器在脚本结束后保持独立运行
修改后的完整代码(两种方案可选)
方案一:用阻塞语句保持浏览器打开
from selenium import webdriver from selenium.webdriver.chrome.service import Service driver_path = r"C:\Users\Acer\Desktop\other\chromedriver.exe" service = Service(driver_path) driver = webdriver.Chrome(service=service) driver.get("https://www.youtube.com/") # 按回车键后才关闭浏览器 input("按回车键关闭浏览器...") driver.quit()
方案二:用ChromeOptions让浏览器独立运行
from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.chrome.options import Options driver_path = r"C:\Users\Acer\Desktop\other\chromedriver.exe" service = Service(driver_path) options = Options() # 设置浏览器在脚本结束后保持打开 options.add_experimental_option("detach", True) driver = webdriver.Chrome(service=service, options=options) driver.get("https://www.youtube.com/")
内容的提问来源于stack exchange,提问作者Piratdj.10
相关产品推荐
相关产品推荐

