如何修复Python+Selenium登录代码中的executable_path参数错误
问题原因排查
- Selenium版本API变更:Selenium 4.x移除了
webdriver.Chrome()的executable_path直接参数,改用Service类封装驱动路径后传入,你的代码已导入ChromeService但未正确使用。 - 驱动路径不完整:代码中
executable_path= r'C:\Program Files (x86)'仅指定了文件夹,未指向具体的chromedriver.exe文件,即使参数合法也会找不到驱动。 - 冗余代码未利用:代码已导入
webdriver_manager相关模块,却仍手动指定路径,既繁琐又易出现Chrome浏览器与驱动版本不匹配的问题。
修复方案
提供两种修复方式,推荐第二种自动管理驱动的方案:
方案1:手动指定驱动路径(适配Selenium 4.x)
修改驱动初始化代码,通过ChromeService传递完整的驱动路径:
# 替换原driver初始化代码 service = ChromeService(executable_path=webdriver_path) # 使用之前定义的完整路径变量 driver = webdriver.Chrome(service=service, options=options)
同时需确保options.binary_location填写正确的Chrome浏览器路径,示例:
options.binary_location = r'C:\Program Files\Google\Chrome\Application\chrome.exe'
方案2:使用WebDriver Manager自动管理驱动(推荐)
无需手动下载和指定驱动路径,工具会自动匹配Chrome版本下载对应驱动,避免版本兼容问题:
# 替换原driver初始化代码 driver = webdriver.Chrome( service=ChromeService(ChromeDriverManager().install()), options=options )
若Chrome安装在默认路径,options.binary_location可直接删除,Selenium会自动查找浏览器位置。
完整修复后的代码示例
from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.chrome.service import Service as ChromeService from webdriver_manager.chrome import ChromeDriverManager # Set the login credentials username = 'xxxxxx' password = 'xxxxxxxx' # Configure the WebDriver options options = webdriver.ChromeOptions() # 填写真实的Chrome浏览器路径,默认路径可省略此行 options.binary_location = r'C:\Program Files\Google\Chrome\Application\chrome.exe' # 用WebDriver Manager自动初始化驱动 driver = webdriver.Chrome( service=ChromeService(ChromeDriverManager().install()), options=options ) # Navigate to the login page driver.get('https://sph.synxis.com/pms-web-ui/login#/logout-success') # Wait for the login page to load wait = WebDriverWait(driver, 10) login_form = wait.until(EC.presence_of_element_located((By.ID, 'login-form'))) # Fill in the login form username_input = driver.find_element(By.ID, 'username') password_input = driver.find_element(By.ID, 'password') username_input.send_keys(username) password_input.send_keys(password) # Submit the login form password_input.send_keys(Keys.RETURN) # 可根据需求添加登录后的等待逻辑,例如等待首页元素加载 # wait.until(EC.presence_of_element_located((By.ID, 'home-page-target-element'))) # Close the browser driver.quit()
内容的提问来源于stack exchange,提问作者Fraz Naqvi
相关产品推荐
相关产品推荐

