亲测好用!!!!!!!!!!!当你安装谷歌浏览器后还需要下载安装同版本的驱动,不要再去网上找驱动自己配置了,直接执行以下代码,帮你轻松匹配浏览器版本。省心省力。快去试试吧

import os
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from webdriver_manager.chrome import ChromeDriverManager
from webdriver_manager.core.driver_cache import DriverCacheManager
#--------------------安装和浏览器匹配的驱动-------------------------
# 1. 定义 D 盘的驱动存放路径
# 确保这个文件夹存在,如果不存在代码会自动创建
DRIVER_DIR = r"D:\app\ChromeDriver"
os.makedirs(DRIVER_DIR, exist_ok=True)

print(f"正在将驱动下载/缓存到: {DRIVER_DIR} ...")

# 2. 配置 CacheManager,指定缓存路径为 D 盘
# 这样 webdriver-manager 就会把下载好的 chromedriver.exe 放在这里
cache_manager = DriverCacheManager(root_dir=DRIVER_DIR)

# 3. 初始化 Driver Manager,使用自定义的 cache_manager
# driver_version="145.0.7632.117" 可以显式指定版本,不写则自动匹配当前浏览器
manager = ChromeDriverManager(cache_manager=cache_manager)

try:
    # install() 会下载驱动到 D:\Drivers\ChromeDriver\.wdm\drivers\chromedriver\win64\...
    # 并返回最终 executable 的完整路径
    driver_path = manager.install()

    print(f"✅ 驱动已就绪,路径: {driver_path}")

    # 4. 启动浏览器
    options = Options()
    # 如果你的 Chrome 也在 D 盘,记得加上这一行,否则注释掉
    # options.binary_location = r"D:\Program Files\Google\Chrome\Application\chrome.exe"

    service = Service(driver_path)
    driver = webdriver.Chrome(service=service, options=options)

    print("🚀 浏览器启动成功!")
    driver.get("https://www.baidu.com")
    print(f"标题: {driver.title}")

except Exception as e:
    print(f"❌ 错误: {e}")
finally:
    if 'driver' in locals():
        driver.quit()
Logo

小龙虾开发者社区是 CSDN 旗下专注 OpenClaw 生态的官方阵地,聚焦技能开发、插件实践与部署教程,为开发者提供可直接落地的方案、工具与交流平台,助力高效构建与落地 AI 应用

更多推荐