pytest执行Selenium脚本报chromedriver需在PATH路径可用错误
问题根因
两个报错本质是代码写法不匹配pytest执行逻辑+路径配置错误共同导致:
- 缩进错误:你贴的代码中
driver = webdriver.Chrome(...)及后续初始化代码缩进和类内其他属性不一致,在类加载阶段就会提前执行驱动初始化,而非等测试用例执行时触发 - 路径格式错误:Linux系统下绝对路径以单斜杠开头,你写的
//home//Downloads//chromedriver是双斜杠开头,会被识别为无效路径,Selenium Service类找不到chromedriver可执行文件,就会抛出基类的NotImplementedError: this method needs to be implemented in a sub class异常,后续连锁抛出WebDriverException: the executable chromedriver needs to be available in the path错误 - 测试逻辑位置错误:你把驱动初始化、页面打开、页面对象实例化的逻辑全写在测试类的类属性位置,pytest收集用例时会把类属性的
hp识别为待注入的fixture,但你没有对应定义这个fixture,直接给测试方法传参会找不到依赖 - 生命周期错误:类级别的driver实例会被所有测试用例共享,用例间易产生污染,你把
driver.close()写在单个测试方法中,多场景测试时后续用例会直接丢失可用驱动 - 直接跑脚本不报错的原因:直接运行脚本时,类定义完成就会执行类属性的初始化代码,此时工作目录和路径解析逻辑和pytest导入模块时的逻辑不同,刚好能识别到你的驱动路径,所以可以正常运行
- 类名不符合规范:pytest默认收集
Test开头的测试类,你写的HomePageTest不符合默认收集规则,可能出现用例识别异常
修复方案
- 把驱动初始化、浏览器启动、页面对象实例化、驱动销毁的逻辑全部移到pytest fixture中管理,不要写在测试类的类属性位置
- 修正chromedriver路径为Linux标准绝对路径,执行
chmod +x /home/Downloads/chromedriver给驱动加可执行权限 - 统一代码缩进,Python类内代码统一缩进4个空格
- 把驱动关闭逻辑放到fixture的teardown阶段,不要写在单个测试方法内
- 测试类名以
Test开头,符合pytest的默认用例收集规则,避免用例收集失败
修正后代码
首先在测试目录下新建conftest.py存放公共fixture:
import pytest from selenium.webdriver.chrome.service import Service from selenium import webdriver # 替换为你自己的HomePage类导入路径 from your_page_module import HomePage @pytest.fixture(scope="class") def driver(): # 修正为正确的chromedriver绝对路径 serv_obj = Service('/home/Downloads/chromedriver') opts = webdriver.ChromeOptions() opts.add_argument('--headless') opts.add_argument("--no-sandbox") driver = webdriver.Chrome(service=serv_obj, options=opts) yield driver # 所有用例执行完成后关闭驱动 driver.quit() @pytest.fixture(scope="class") def hp(driver): driver.get('替换为你的实际站点URL') print(driver.title) return HomePage(driver)
调整后的test_home-page.py代码:
class TestHomePage: def test_logo(self, hp): assert hp.get_logo() == '替换为实际预期的logo地址'
内容的提问来源于stack exchange,提问作者kishore sai anil
相关产品推荐
相关产品推荐

