如何使用python在Selenium中以编程方式使Firefox变得无头?

如何使用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?