selenium 指定 chrome 和 chromedriver 位置
2024-08-31 tech python selenium chromedriver chrome 2 mins 815 字

使用 webdriver.Chrome 时
- 通过
chrome_options.binary_location参数指定 Chrome 浏览器的路径 - 通过 Service 的
executable_path参数指定chromedriver.exe的位置
以下是一个 Windows 示例代码:
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对象。