selenium4如何指定chrome和firefox的驱动(driver)路径

python+pytest+selenium框架的自动化测试脚本。

原本用的chrome,很久没用了,今天执行,发现chrome偷偷升级,我的chromedriver版本不对了。。。鉴于访问chrome相关网站太艰难,决定弃用chrome,改用firefox。因为,firefox可以自己决定是否升级浏览器:

改倒是很快,问题是,改完了执行的时候发现,有时候可以,有时候找不到driver。。。。因为我是这么用的:

python 复制代码
driver = webdriver.Firefox()

这里未指定geckodriver的路径,默认使用执行目录下的driver。

浏览器驱动放在项目的根目录下,执行时,若从项目根目录下的pytest.main()执行,自然没有问题。但是当我写脚本,单独调试的时候,执行目录变成每一个test case所在的目录,即%项目根目录%/case/子目录/test_XXX.py

所以,它找不到浏览器驱动。。。

我需要指定浏览器驱动的位置,让它每次都去同一个地方找。网上搜了一圈,要么是chromedriver的指定方法,要么是让我用参数execute_path指定路径,但是,运行时发现这个参数非法。。。

自己去查官网API(7. WebDriver API --- Selenium Python Bindings 2 documentation),一打开看到这样一个列表

受到启发,于是仿着chrome,指定了firefox驱动的路径,如下:

指定chrome driver的路径

python 复制代码
import sys
import os
from selenium import webdriver
from selenium.webdriver.chrome.service import Service

driver_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(sys.executable)))),'chromedriver.exe')
service = Service(executable_path=driver_path)
options = webdriver.ChromeOptions()
driver = webdriver.Chrome(service=service, options=options)

指定firefox driver的路径

python 复制代码
import sys
import os
from selenium import webdriver
from selenium.webdriver.firefox.options import Options


driver_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(sys.executable)))),
                               'geckodriver.exe')
service = Service(executable_path=driver_path)
options = webdriver.FirefoxOptions()
driver = webdriver.Firefox(service=service, options=options)
相关推荐
linweidong6 小时前
中科闻歌Java面试题及参考答案
java·python·大模型·提示词·ai agent·mcp·rag原理
小玮看世界6 小时前
[Python]OD算法在OD实际运用转化参考清单
开发语言·python·算法
萧鼎6 小时前
2026实战:用 tomlkit 优雅读写 TOML 配置,告别手写解析器
python·开源·教程·python库
小刘在重生~7 小时前
Java 常用类|包装类 装箱拆箱、Integer 缓存面试题
java·python·缓存
2601_962099468 小时前
Python xlwt设置excel单元格字体及格式
python·excel·xlwt·样式设置·单元格格式
奇牙coding1238 小时前
GPT-6-Astra API 接入教程:OpenRouter 路由配置 + Python/curl 示例 + 静默降级踩坑
开发语言·python·gpt·ai
2601_962298278 小时前
Python与Selenium结合的Web自动化测试全流程实践教程
自动化测试·python·selenium·web测试·pageobjectmodel
天衍四九-9 小时前
第一章:从 LLM 到 Agent —— DeepSeek Harness 入门
网络·数据库·人工智能·python
529宝宝起名网9 小时前
用 Python 实现名字寓意评分算法:基于 NLP 语义分析的名字内涵深度评估
python·算法·自然语言处理
2601_962298679 小时前
Python:对象缓存优化机制(CPython)
python·性能优化·内存优化·cpython·对象缓存