在Python Selenium中为Chrome和Firefox浏览器开启headless模式

我们通常会使用Selenium编写UI测试,为浏览器开启Headless模式(执行操作时不显示GUI窗口)会很方便。最新版本的Chrome和Firefox中,均已支持headless模式。

在Selenium中,为这两个浏览器开启headless模式的方式基本相同:

Chrome:

from selenium import webdriver

options = webdriver.ChromeOptions()
options.add_argument('headless')
driver = webdriver.Chrome(options=options)

Firefox:

from selenium import webdriver

options = webdriver.FirefoxOptions()
options.add_argument('headless')
driver = webdriver.Firefox(options=options)

我提交的PR#5120添加了和Chrome相同的导入接口,如果你使用Selenium小于3.8.0版本,则需要将上面的webdriver.FirefoxOptions()替换为webdriver.firefox.options.Options()

另外,你也可以使用环境变量MOZ_HEADLESS 来为Firefox开启headless模式:

import os
from selenium import webdriver

os.environ['MOZ_HEADLESS'] = '1'  # <- this line
driver = webdriver.Firefox()

本文基于我在Stack Overflow的这篇回答:https://stackoverflow.com/a/47481793/5511849

在Python Selenium中为Chrome和Firefox浏览器开启headless模式》上有3条评论

  1. 头像张小影

    请问在headless模式下,如果页面有alert弹框,自动化测试时该怎样给弹框截图呢?我试了下面这两种方法,都截的时当前电脑的屏幕,不是后台headless的图,请问大神怎么办

    方法1:
    import pyautogui
    im1 = pyautogui.screenshot()
    im1.save(‘my_screenshot.png’)

    方法2:
    from PIL import ImageGrab
    im = ImageGrab.grab()
    im.save(‘my_screenshot.png’)

    回复
    1. 头像李辉 文章作者

      我也不太清楚哎,但是 headless 模式的话是没有图形界面出现,所以你的这两种方法肯定不行。你可以试试 Selenium 自带的截图接口。

      回复
      1. 头像张小影

        谢谢哈,但是正常可以使用selenium自带的get_screenshot_as_file()方法截图,但是alert不是网页的一部分,所以截不了…….

        回复

李辉进行回复 取消回复

电子邮件地址不会被公开,必填项已用 * 标出。