Selenium+Pytest项目GitLab CI运行报错及配置方案咨询
GitLab CI下Selenium+Pytest流水线配置指引
报错核心原因
- 你当前测试运行容器内没有安装Chrome浏览器,webdriver_manager 初始化时尝试探测本地Chrome版本信息,因无对应环境直接触发报错
- 流水线已经配置了独立的
selenium/standalone-chrome服务容器,但原有测试逻辑走的是本地浏览器启动模式,没有建立和服务容器的远程连接,逻辑和CI架构完全不匹配
分步实现目标
全程覆盖两个核心要求:全依赖安装、测试正常执行
- 第一步:固定Python运行环境,对齐本地3.8版本,避免Python版本差带来的依赖兼容问题,直接选用官方
python:3.8-slim作为测试运行容器镜像 - 第二步:移除webdriver_manager相关依赖调用逻辑,该工具为本地开发场景设计,CI环境不需要——
selenium/standalone-chrome服务镜像已经预装了严格版本匹配的Chrome浏览器、ChromeDriver组件,无需额外下载驱动 - 第三步:修改测试setup夹具,改为通过远程WebDriver协议连接独立Selenium服务容器,补充容器环境必需的Chrome运行参数
- 第四步:整理流水线的依赖安装逻辑,一次性安装全部Python侧依赖(pytest、selenium、allure-pytest),无重复安装逻辑
配置参考代码
修改后的conftest.py测试夹具
import pytest from selenium import webdriver from selenium.webdriver.chrome.options import Options @pytest.fixture() def setup(request): options = Options() # 容器环境Chrome必加参数,避免运行权限、内存问题 options.add_argument("--headless=new") options.add_argument("--no-sandbox") options.add_argument("--disable-dev-shm-usage") options.add_argument("--disable-gpu") options.page_load_strategy = 'normal' # 连接流水线内的Selenium Chrome服务容器 driver = webdriver.Remote( command_executor="http://selenium__standalone-chrome:4444/wd/hub", options=options ) request.cls.driver = driver driver.maximize_window() yield driver.quit()
修改后的.gitlab-ci.yml配置
stages: - test e2e:chrome: # 对齐本地Python 3.8版本的运行环境 image: python:3.8-slim # 独立Selenium Chrome服务,自带匹配版本的Chrome和ChromeDriver services: - name: selenium/standalone-chrome alias: selenium__standalone-chrome before_script: - python -V # 一次性安装所有Python依赖,带缓存参数加速安装 - pip install --no-cache-dir pytest selenium allure-pytest script: # 执行测试同时生成Allure结果目录 - python -m pytest Tvn24_Tests/Login_By_Facebook_Test.py --alluredir=allure-results # 测试无论成功失败都留存Allure原始结果,方便后续排障 artifacts: when: always paths: - allure-results
新手排坑提示
- 不要在CI环境中保留
webdriver_manager的导入和调用,否则会因为测试容器内无Chrome环境重复触发版本探测报错 - 远程连接的地址必须和服务配置的alias完全一致,避免GitLab CI服务域名解析失败
- 如果遇到页面交互异常、内存溢出类报错,优先检查Chrome的容器参数是否全部添加
- 不需要在Python测试容器内安装Chrome相关系统组件,所有浏览器运行逻辑全部在独立Selenium服务容器内完成,可大幅减少流水线运行资源消耗
内容的提问来源于stack exchange,提问作者Łukasz Gil
相关产品推荐
相关产品推荐

