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


有几种方法,但不是简单的“设置配置值”。除非你投资了一个无头浏览器,这并不适合每个人的需求,它是一个有点hack:

如何隐藏Firefox窗口(硒WebDriver)?

and

是否有可能隐藏在硒RC浏览器?

你可以'supposed ',传入一些参数到Chrome,特别是:——no-startup-window

请注意,对于某些浏览器,特别是Internet Explorer,不让它集中运行会影响您的测试。

你也可以使用AutoIt来隐藏窗口。


在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服务器?


如果你在Python中使用Selenium web驱动程序,你可以使用PyVirtualDisplay,它是Xvfb和Xephyr的Python包装器。

PyVirtualDisplay需要Xvfb作为依赖项。在Ubuntu上,首先安装Xvfb:

sudo apt-get install xvfb

然后从PyPI安装PyVirtualDisplay:

pip install pyvirtualdisplay

使用PyVirtualDisplay在无头模式下的Python Selenium脚本示例:

    #!/usr/bin/env python

    from pyvirtualdisplay import Display
    from selenium import webdriver

    display = Display(visible=0, size=(800, 600))
    display.start()

    # Now Firefox will run in a virtual display.
    # You will not see the browser.
    browser = webdriver.Firefox()
    browser.get('http://www.google.com')
    print browser.title
    browser.quit()

    display.stop()

EDIT

最初的答案是在2014年发布的,现在我们正处于2018年的风口浪尖。和其他事物一样,浏览器也在进步。Chrome现在有一个完全无头的版本,它消除了使用任何第三方库来隐藏UI窗口的需要。示例代码如下:

    from selenium import webdriver
    from selenium.webdriver.chrome.options import Options

    CHROME_PATH = '/usr/bin/google-chrome'
    CHROMEDRIVER_PATH = '/usr/bin/chromedriver'
    WINDOW_SIZE = "1920,1080"

    chrome_options = Options()
    chrome_options.add_argument("--headless")
    chrome_options.add_argument("--window-size=%s" % WINDOW_SIZE)
    chrome_options.binary_location = CHROME_PATH

    driver = webdriver.Chrome(executable_path=CHROMEDRIVER_PATH,
                              chrome_options=chrome_options
                             )
    driver.get("https://www.google.com")
    driver.get_screenshot_as_file("capture.png")
    driver.close()

我建议使用PhantomJS。更多信息,请访问魅影官方网站。

据我所知,PhantomJS只适用于Firefox…

下载PhantomJS. exe后,您需要将其导入到您的项目中,如下图所示。

我把我的放在:common→Library→phantomjs.exe

现在,在Selenium代码中所要做的就是更改该行

browser = webdriver.Firefox()

比如

import os
path2phantom = os.getcwd() + "\common\Library\phantomjs.exe"
browser = webdriver.PhantomJS(path2phantom)

PhantomJS的路径可能会有所不同……想怎么改就怎么改:)

这个方法对我有用,我很确定它对你也有用;)


下面是一个适合我的。net解决方案:

在http://phantomjs.org/download.html下载PhantomJS。

从下载文件夹中的bin文件夹中复制.exe文件,并将其粘贴到Visual Studio项目的bin调试/发布文件夹中。

使用

using OpenQA.Selenium.PhantomJS;

在你的代码中,像这样打开驱动程序:

PhantomJSDriver driver = new PhantomJSDriver();
using (driver)
{
   driver.Navigate().GoToUrl("http://testing-ground.scraping.pro/login");
   // Your code here
}

Chrome 57有一个选项来传递——headless标志,这使得窗口不可见。

这个标志不同于——no-startup-window,因为最后一个标志不会启动一个窗口。它是用来托管后台应用程序,正如这页所说。

Java代码传递标志到Selenium webdriver (ChromeDriver):

ChromeOptions options = new ChromeOptions();
options.addArguments("--headless");
ChromeDriver chromeDriver = new ChromeDriver(options);

要在没有浏览器的情况下运行,可以在headless模式下运行。

我给你们看一个Python中的例子,它现在对我有用

from selenium import webdriver


options = webdriver.ChromeOptions()
options.add_argument("headless")
self.driver = webdriver.Chrome(executable_path='/Users/${userName}/Drivers/chromedriver', chrome_options=options)

我还在谷歌的官方网站https://developers.google.com/web/updates/2017/04/headless-chrome上给大家补充了更多的信息


自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不再维护了!


它可能在选项中。下面是相同的Java代码。

        ChromeOptions chromeOptions = new ChromeOptions();
        chromeOptions.setHeadless(true);
        WebDriver driver = new ChromeDriver(chromeOptions);

如果你使用的是Ubuntu (Gnome),一个简单的解决方法是安装Gnome扩展auto-move-window: https://extensions.gnome.org/extension/16/auto-move-windows/

然后设置浏览器(如。Chrome)到另一个工作空间(例如。2).浏览器将在其他工作空间中静默运行,不再打扰您。你仍然可以在你的工作空间中使用Chrome浏览器,不受任何干扰。


我的chromedriver使用Python和options.add_argument(“headless”)也有同样的问题,但后来我意识到如何修复它,所以我把它放在下面的代码中:

opt = webdriver.ChromeOptions()
opt.arguments.append("headless")

这是一个简单的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')

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


如果你正在使用谷歌Chrome驱动程序,你可以使用这段非常简单的代码(它对我有用):

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

chrome_options = Options()
chrome_options.add_argument("--headless")
driver = webdriver.Chrome('chromedriver2_win32/chromedriver.exe', options=chrome_options)
driver.get('https://www.anywebsite.com')

我在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(...)
...

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


实现这一点的一种方法是在headless模式下运行浏览器。这样做的另一个好处是测试执行得更快。

请找到下面的代码在Chrome浏览器中设置无头模式。

package chrome;

public class HeadlessTesting {

    public static void main(String[] args) throws IOException {
        System.setProperty("webdriver.chrome.driver",
                "ChromeDriverPath");
        ChromeOptions options = new ChromeOptions();
        options.addArguments("headless");
        options.addArguments("window-size=1200x600");
        WebDriver driver = new ChromeDriver(options);
        driver.get("https://contentstack.built.io");
        driver.get("https://www.google.co.in/");
        System.out.println("title is: " + driver.getTitle());
        File scrFile = ((TakesScreenshot) driver)
                .getScreenshotAs(OutputType.FILE);
        FileUtils.copyFile(scrFile, new File("pathTOSaveFile"));
        driver.quit();
    }
}

只需添加一个简单的“无头”选项参数。

from selenium import webdriver

options = webdriver.ChromeOptions()
options.add_argument("--headless")
driver = webdriver.Chrome("PATH_TO_DRIVER", options=options)

利用它……

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

options = Options()
options.headless = True
driver = webdriver.Chrome(CHROMEDRIVER_PATH, chrome_options=options)