我有一个Selenium测试套件,它运行许多测试,在每次新的测试中,它都会在我打开的任何其他窗口之上打开一个浏览器窗口。在当地工作很不和谐。有没有办法告诉硒或OS (Mac)在后台打开窗口?


当前回答

我在Windows中使用了这段代码,得到了答案(参考这里):

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

Options = Options()
Options.headless = True

Driver = webdriver.Firefox(options=Options, executable_path='geckodriver.exe')
Driver.get(...)
...

但我没有在其他浏览器上测试它。

其他回答

在Windows上,你可以使用win32gui:

import win32gui
import win32con
import subprocess

class HideFox:
    def __init__(self, exe='firefox.exe'):
        self.exe = exe
        self.get_hwnd()

    def get_hwnd(self):
      win_name = get_win_name(self.exe)
      self.hwnd = win32gui.FindWindow(0,win_name)

    def hide(self):
        win32gui.ShowWindow(self.hwnd, win32con.SW_MINIMIZE)
        win32gui.ShowWindow(self.hwnd, win32con.SW_HIDE)

    def show(self):
        win32gui.ShowWindow(self.hwnd, win32con.SW_SHOW)
        win32gui.ShowWindow(self.hwnd, win32con.SW_MAXIMIZE)

def get_win_name(exe):
    ''' Simple function that gets the window name of the process with the given name'''
    info = subprocess.STARTUPINFO()
    info.dwFlags |= subprocess.STARTF_USESHOWWINDOW
    raw = subprocess.check_output('tasklist /v /fo csv', startupinfo=info).split('\n')[1:-1]
    for proc in raw:
        try:
            proc = eval('[' + proc + ']')
            if proc[0] == exe:
                return proc[8]
        except:
            pass
    raise ValueError('Could not find a process with name ' + exe)

例子:

hider = HideFox('firefox.exe') # Can be anything, e.q., phantomjs.exe, notepad.exe, etc.
# To hide the window
hider.hide()
# To show again
hider.show()

然而,这个解决方案有一个问题-使用send_keys方法使窗口显示出来。你可以使用JavaScript来处理它,不显示窗口:

def send_keys_without_opening_window(id_of_the_element, keys)
    YourWebdriver.execute_script("document.getElementById('" + id_of_the_element + "').value = '" + keys + "';")

在*nix上,你也可以运行一个无头的X Window服务器,比如Xvfb,并将DISPLAY环境变量指向它:

用于测试的假X服务器?

自Chrome 57以来,你有无头的论点:

var options = new ChromeOptions();
options.AddArguments("headless");
using (IWebDriver driver = new ChromeDriver(options))
{
    // The rest of your tests
}

Chrome无头模式比UI版本性能提高30.97%。另一个无头驱动程序PhantomJS比Chrome的无头模式好34.92%。

幻影JSDriver

using (IWebDriver driver = new PhantomJSDriver())
{
     // The rest of your test
}

Firefox无头模式的性能比UI版本提高了3.68%。这很令人失望,因为Chrome的无头模式比UI模式的时间长了30%。另一个无头驱动程序PhantomJS比Chrome的无头模式好34.92%。令我惊讶的是,Edge浏览器击败了所有这些浏览器。

var options = new FirefoxOptions();
options.AddArguments("--headless");
{
    // The rest of your test
}

这可以从Firefox 57+中获得

Firefox无头模式的性能比UI版本提高了3.68%。这很令人失望,因为Chrome的无头模式比UI模式的时间长了30%。另一个无头驱动程序PhantomJS比Chrome的无头模式好34.92%。令我惊讶的是,Edge浏览器击败了所有这些浏览器。

注意:PhantomJS不再维护了!

我在Windows中使用了这段代码,得到了答案(参考这里):

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

Options = Options()
Options.headless = True

Driver = webdriver.Firefox(options=Options, executable_path='geckodriver.exe')
Driver.get(...)
...

但我没有在其他浏览器上测试它。

这是一个简单的Node.js解决方案,适用于新版本4。x(也可能是3.x)的硒。

const { Builder } = require('selenium-webdriver')
const chrome = require('selenium-webdriver/chrome');

let driver = await new Builder().forBrowser('chrome').setChromeOptions(new chrome.Options().headless()).build()

await driver.get('https://example.com')

火狐

const { Builder } = require('selenium-webdriver')
const firefox = require('selenium-webdriver/firefox');

let driver = await new Builder().forBrowser('firefox').setFirefoxOptions(new firefox.Options().headless()).build()

await driver.get('https://example.com')

整个程序都在后台运行。这正是我们想要的。