如何使用 Python 在 Selenium 中以编程方式使 Firefox 无头? [英] How to make Firefox headless programmatically in Selenium with Python?
问题描述
我正在使用 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 视频
- 通过 Selenium 3.5.2 (Java) 在 Headless 模式下的 Mozilla Firefox
- 使用 Headless Chrome 通过 Selenium Java 登录 Gmail 帐户
如何配置 ChromeDriver 以通过 Selenium 在 Headless 模式下启动 Chrome 浏览器?
这篇关于如何使用 Python 在 Selenium 中以编程方式使 Firefox 无头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!