已弃用警告:EXECUTABLE_PATH已弃用Selenium Python

2022-02-20 00:00:00 python selenium selenium4

问题描述

我正在使用SUPEIME编写Python脚本。以下代码用于python中的Selenium使用Webdriver_manager包自动安装驱动程序

# pip install webdriver-manager
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By

driver = webdriver.Chrome(ChromeDriverManager().install())
driver.maximize_window()

#s=Service(path)
#driver=webdriver.Chrome(service=s)
driver.get('https://www.google.com')
driver.find_element(By.NAME, 'q').send_keys('Yasser Khalil')

代码运行正常,但我收到类似的警告

Demo.py:7: DeprecationWarning: executable_path has been deprecated, please pass in a Service object
  driver = webdriver.Chrome(ChromeDriverManager().install())

如何修复此类错误?


解决方案

此错误消息.

DeprecationWarning: executable_path has been deprecated, please pass in a Service object

.表示键executable_path将在即将发布的版本中弃用。

此更改与Selenium 4.0 Beta 1changelog一致,其中提到:

不推荐使用驱动程序实例化中除OptionsService参数之外的所有参数。(#9125,#9128)


解决方案

使用selenium4作为键executable_path已弃用,您必须将Service()类的实例与ChromeDriverManager().install()命令一起使用,如下所述。

前提条件

确保:

  • Selenium升级到v4.0.0

    pip3 install -U selenium
    
  • Python的WebDriver Manager已安装

    pip3 install webdriver_manager
    

您可以在ModuleNotFoundError: No module named 'webdriver_manager' error even after installing webdrivermanager

中找到有关安装WebDriver Manager for Python的详细讨论

Selenium v4兼容代码挡路

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager

driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
driver.get("https://www.google.com")

控制台输出:

[WDM] - ====== WebDriver manager ======
[WDM] - Current google-chrome version is 96.0.4664
[WDM] - Get LATEST driver version for 96.0.4664
[WDM] - Driver [C:UsersAdmin.wdmdriverschromedriverwin3296.0.4664.45chromedriver.exe] found in cache

您可以在Selenium ChromeDriver issue using Webdriver Manager for Python

中找到有关安装WebDriver Manager for Python的详细讨论

如果要传递Options()对象,可以使用:

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

options = Options()
options.add_argument("start-maximized")
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options)
driver.get("https://www.google.com")

TL;DR

您可以在以下地址找到相关的Bug报告/拉取请求:

  • 错误报告:deprecate all but Options and Service arguments in driver instantiation
  • 拉取请求:deprecate all but Options and Service arguments in driver instantiation

相关文章