如何在GitLab CI的Selenium UI测试中设置1920x1080分辨率?
问题
我有一个基于Python Selenium的测试框架,在GitLab CI中启动浏览器并运行UI测试。测试显示当前主机屏幕分辨率为1360x1020,希望调整为1920x1080,让UI测试在标准桌面分辨率下运行。请问是否可以设置浏览器运行时的屏幕分辨率?
我的GitLab CI配置如下:
image: python:3.11 test: stage: test-automation services: - name: selenium/standalone-chrome:latest script: - apt-get update - apt-get install -y x11-xserver-utils - xrandr | grep '*' | awk '{print $1}' #error "Can't open display" - #python selenium project running on the chrome service above
我尝试使用xrandr命令,但出现了“Can't open display”的错误,无法访问显示设备。
解决方案
1. 在Selenium代码中直接设置浏览器窗口大小
这是最直接可靠的方式,不用折腾CI环境的显示设置,初始化浏览器时直接指定窗口尺寸即可:
from selenium import webdriver from selenium.webdriver.chrome.options import Options chrome_options = Options() # 强制设置浏览器窗口为1920x1080 chrome_options.add_argument("--window-size=1920,1080") # 如果需要全屏运行,也可以替换成下面的参数 # chrome_options.add_argument("--start-fullscreen") # 连接到GitLab CI中运行的Selenium服务 driver = webdriver.Remote( command_executor='http://selenium__standalone-chrome:4444/wd/hub', options=chrome_options )
2. 配置Selenium服务容器的启动参数
如果想让所有测试默认使用1920x1080分辨率,可以在GitLab CI的services配置里添加启动参数,直接指定Selenium容器的虚拟屏幕分辨率:
services: - name: selenium/standalone-chrome:latest command: ["--screen-resolution", "1920x1080x24"]
这样Selenium容器启动时会自动设置好虚拟显示器的分辨率,不需要在主Python容器里执行xrandr命令。
关于xrandr报错的原因
你在主Python容器里跑xrandr,但主容器本身没有运行X服务器,而Selenium服务是独立的容器,有自己的虚拟显示环境。主容器根本访问不到Selenium容器的显示设备,所以才会出现"Can't open display"的错误。直接从Selenium配置或代码入手才是正确的解决方向。
内容的提问来源于stack exchange,提问作者pretzelz
相关产品推荐
相关产品推荐

