如何隐藏Firefox窗口(Selenium WebDriver)?
当我同时运行多个测试时,我不想让Firefox浏览器窗口一直显示在屏幕上。我可以用 selenium.minimizeWindow()
把它最小化,但我其实不想这样做。
有没有办法把Firefox窗口隐藏起来?我正在使用Firefox的WebDriver。
14 个回答
只需要添加以下代码。
import os
os.environ['MOZ_HEADLESS'] = '1'
driver = webdriver.Firefox()
Python
隐藏浏览器最简单的方法是安装 PhantomJS。然后,把这一行:
driver = webdriver.Firefox()
改成:
driver = webdriver.PhantomJS()
你其他的代码就不用改了,这样就不会打开浏览器了。如果你需要调试,可以在代码的不同步骤使用 driver.save_screenshot('screen.png')
来保存屏幕截图,或者再切换回 Firefox 的 webdriver。
在 Windows 系统上,你需要指定 phantomjs.exe 的路径:
driver = webdriver.PhantomJS('C:\phantomjs-1.9.7-windows\phantomjs.exe')
Java
可以看看 Ghost Driver: 如何用 Java 运行 ghostdriver 和 Selenium
C#
如何在 PhantomDriver(无头浏览器)中隐藏 FirefoxDriver(使用 Selenium)而不出现 findElement 函数错误?
最后,我找到了一个解决方案,适合那些在Windows机器上运行测试的人。虽然这个实现不是用Java写的,但你可以很轻松地做到。
使用 AutoIt
工具。它可以处理Windows窗口,并且是免费的。
安装AutoIt: http://www.autoitscript.com/site/autoit/downloads/
打开编辑器,写下面的代码来隐藏任何窗口。
AutoItSetOption("WinTitleMatchMode", 2) WinSetState("Title Of Your Window", "", @SW_HIDE)
要让窗口重新显示,可以使用下面的代码行。
AutoItSetOption("WinTitleMatchMode", 2) WinSetState("Title Of Your Window", "", @SW_SHOW)
WinTitleMatchMode
有不同的选项,可以用来匹配窗口标题。1 = Match the title from the start (default)` 2 = Match any substring in the title 3 = Exact title match 4 = Advanced mode, see Window Titles & Text (Advanced)
我所做的是:我创建了一个小程序的 .exe 文件,并将一个参数作为命令行参数传递,像下面这样。
Runtime.getRuntime().exec("C:/Diiinnovation/HideNSeek.exe 0 \"" + "Mozilla Firefox" + "\"");
在 HideNSeek.exe
中 - 我有下面的AutoIt代码:
AutoItSetOption("WinTitleMatchMode", 1)
if $CmdLine[0] > 0 Then
if $CmdLine[1] == 0 Then
WinSetState($CmdLine[2], "", @SW_HIDE)
ElseIf $CmdLine[1] == 1 Then
WinSetState($CmdLine[2], "", @SW_SHOW)
Else
EndIf
EndIf
$CmdLine[]
是一个数组,里面会包含所有的命令行参数...
$CmdLine[0] = number of Parameter
$CmdLine[1] = 1st Parameter after Exe Name
...
如果窗口标题中有空格,你需要用双引号将其包起来,像上面那样传递作为命令行参数。
下面的代码行会执行AutoIt的exe,如果我在第一个参数中传入'0',那么它会隐藏窗口;如果我传入'1',那么它会显示与标题匹配的窗口。
Runtime.getRuntime().exec("C:/Diiinnovation/HideNSeek.exe 0 \"" + "Mozilla Firefox" + "\"");
希望这对你有帮助。谢谢!