在 Windows 下使用 webdriver.Chrome
时,可以通过 webdriver.Chrome
的 executable_path
参数指定 chromedriver.exe
的位置,同时通过 chrome_options.binary_location
参数指定 Chrome 浏览器的路径。以下是一个示例代码:
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
# 设置 Chrome 浏览器的路径
chrome_options = webdriver.ChromeOptions()
chrome_options.binary_location = r'C:\Path\To\Your\Chrome\Application\chrome.exe' # 替换为 Chrome 路径
# 指定 chromedriver.exe 的路径
service = Service(executable_path=r'C:\Path\To\Your\chromedriver.exe') # 替换为 chromedriver 路径
# 启动浏览器
driver = webdriver.Chrome(service=service, options=chrome_options)
driver.get('https://www.baidu.com')
关键点:
chrome_options.binary_location
: 设置 Chrome 浏览器可执行文件的路径。executable_path
: 设置 chromedriver.exe
的路径。Service
: 使用 Service
对象指定 chromedriver.exe
的路径。webdriver.Chrome
: 通过 service
参数传入 Service
对象。