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

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

问题描述

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

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:\Utility\BrowserDrivers\geckodriver.exe')
driver.get("http://google.com/")
print ("Headless Firefox Initialized")
driver.quit()


还有另一种方法来完成无头模式.如果您需要在Firefox中禁用或启用无头模式,而无需更改代码,则可以将环境变量MOZ_HEADLESS设置为任何(如果您希望Firefox无头运行),或者不进行设置完全没有.


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


Outro

如何配置ChromeDriver以通过Selenium以无头模式启动Chrome浏览器?


Outro

How to configure ChromeDriver to initiate Chrome browser in Headless mode through Selenium?

这篇关于如何使用python在Selenium中以编程方式使Firefox变得无头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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