Selenium 最新版本驱动Chrome
在 Selenium 4 以后的版本中,使用 webdriver.Chrome() 初始化时,不再使用 executable_path 来指定驱动路径。相反,您应该使用 Service 类来指定 ChromeDriver 的路径。
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.keys import Keys
# 指定 ChromeDriver 的路径
driver_path = 'D:/path/to/chromedriver.exe' # 修改为您的实际路径
# 创建 Service 对象
service = Service(executable_path=driver_path)
# 使用 Service 对象创建 WebDriver 实例
driver = webdriver.Chrome(service=service)
# 访问 Google 主页
driver.get('https://www.google.com')
# 找到搜索框,输入 'Python' 并提交搜索
search_box = driver.find_element(by="name", value='q')
search_box.send_keys('Python')
search_box.send_keys(Keys.RETURN) # 模拟按下回车键
# 等待几秒查看搜索结果
driver.implicitly_wait(10) # 等待10秒
# 关闭浏览器
driver.quit()
在这个代码中,Service 类从 selenium.webdriver.chrome.service 模块导入。通过 Service 类,您可以指定 ChromeDriver 的路径。此外,find_element 方法也进行了更新,增加了明确的 by 和 value 参数,以适应新版本的 Selenium API。
