如何使用 Python 在 Selenium 中以编程方式使 Firefox 无头? [英] How to make Firefox headless programmatically in Selenium with Python?

查看:20
本文介绍了如何使用 Python 在 Selenium 中以编程方式使 Firefox 无头?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 python、selenium 和 firefox 运行此代码,但仍然获得 'head' 版本的 firefox:

I am running this code with python, selenium, and firefox but still get 'head' version of firefox:

binary = FirefoxBinary('C:\Program Files (x86)\Mozilla Firefox\firefox.exe', log_file=sys.stdout)
binary.add_command_line_options('-headless')
self.driver = webdriver.Firefox(firefox_binary=binary)

我也尝试了一些二进制的变体:

I also tried some variations of binary:

binary = FirefoxBinary('C:\Program Files\Nightly\firefox.exe', log_file=sys.stdout)
        binary.add_command_line_options("--headless")

推荐答案

要无头调用 Firefox 浏览器,可以通过 Options() 类设置 headless 属性如下:

To invoke Firefox Browser headlessly, you can set the headless property through Options() class as follows:

from selenium import webdriver
from selenium.webdriver.firefox.options import Options

options = Options()
options.headless = True
driver = webdriver.Firefox(options=options, executable_path=r'C:UtilityBrowserDriversgeckodriver.exe')
driver.get("http://google.com/")
print ("Headless Firefox Initialized")
driver.quit()


还有另一种实现无头模式的方法.如果您需要在 Firefox 中禁用或启用 headless 模式,而无需更改代码,您可以将环境变量 MOZ_HEADLESS 设置为 whatever 如果您希望 Firefox 运行 headless,或者根本不要设置它.


There's another way to accomplish headless mode. If you need to disable or enable the headless mode in Firefox, without changing the code, you can set the environment variable MOZ_HEADLESS to whatever if you want Firefox to run headless, or don't set it at all.

当您使用例如持续集成并且您希望在服务器中运行功能测试但仍然能够在您的 PC 中以正常模式运行测试时,这非常有用.

This is very useful when you are using for example continuous integration and you want to run the functional tests in the server but still be able to run the tests in normal mode in your PC.

$ MOZ_HEADLESS=1 python manage.py test # testing example in Django with headless Firefox

$ export MOZ_HEADLESS=1   # this way you only have to set it once
$ python manage.py test functional/tests/directory
$ unset MOZ_HEADLESS      # if you want to disable headless mode


逐步浏览 YouTube 视频

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆