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)
相关推荐
vicky051719 分钟前
解决 ModuleNotFoundError: No module named ‘torch‘ 笔记
python
wuyk55524 分钟前
Python实战项目02:学生成绩管理系统(控制台|CSV导出|完整落地)
开发语言·python
AlanBruce6 小时前
摩尔信使MThings功能综述与应用使用指南
linux·自动化·plc·mthings·摩尔信使
qq5918406857 小时前
uiautomator2自动化安卓手机操作
python
80s7777 小时前
动态代理和静态代理的区别,动态代理怎么提高网络安全性
python
搞科研的小刘选手8 小时前
【武汉举办 | JPCS出版 | EI稳定检索】2026年智能制造、自动化与控制国际学术会议(IMAC 2026)
自动化·智能制造·控制·学术会议·会议推荐
niucloud-admin9 小时前
JAVA V6 多商户商城 开发文档——job 计划任务开发
java·python·github
小叶肥辉9 小时前
LangChain链和LangGraph图的学习笔记【三】——分别用langchain_openai库和langchain_community库调用大模型
笔记·python·langchain
2401_873479409 小时前
IP属地为什么有时显示外省?用IP查询工具核查动态分配、运营商出口与GeoIP库
python·tcp/ip·ip
海宇AI10 小时前
零信任架构实战:基于海宇柠檬查出险-登记证构建自动化车抵贷核保网关
java·人工智能·架构·自动化