4

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

 3 years ago
source link: https://greyli.com/python-selenium-headless-for-chrome-firefox/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

在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

本条目发布于2018年7月28日。属于技术笔记分类,被贴了 ChromeFirefoxPythonSelenium 标签。 ← Flask Web开发实战番外 Flask test_client()测试客户端为勾选框传递布尔值数据 →

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

  1. 头像张小影 2020年5月26日上午11:27

    请问在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. 头像张小影 2020年5月26日下午1:13

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

        回复

撰写评论 取消回复

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

评论

姓名 *

电子邮件 *

站点

在此浏览器中保存我的名字、电邮和网站。

当有人回复我时,发送电子邮件提醒我。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK