Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/selenium/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Selenium WebDriver能否在后台以静默方式打开浏览器窗口?_Selenium_Selenium Webdriver_Webdriver_Selenium Grid - Fatal编程技术网

Selenium WebDriver能否在后台以静默方式打开浏览器窗口?

Selenium WebDriver能否在后台以静默方式打开浏览器窗口?,selenium,selenium-webdriver,webdriver,selenium-grid,Selenium,Selenium Webdriver,Webdriver,Selenium Grid,我有一个Selenium测试套件,它运行许多测试,在每个新测试中,它会在我打开的任何其他窗口上打开一个浏览器窗口。在当地环境中工作时非常不和谐。有没有办法让Selenium或操作系统(Mac)在后台打开windows?有几种方法,但不是简单的“设置配置值”。除非你投资开发一款无头浏览器,它不适合所有人的需求,否则它有点像黑客: 及 您可以“假定”将一些参数传入Chrome,具体来说:——无启动窗口 请注意,对于某些浏览器,尤其是Internet Explorer,如果没有集中运行它,将损害您

我有一个Selenium测试套件,它运行许多测试,在每个新测试中,它会在我打开的任何其他窗口上打开一个浏览器窗口。在当地环境中工作时非常不和谐。有没有办法让Selenium或操作系统(Mac)在后台打开windows?

有几种方法,但不是简单的“设置配置值”。除非你投资开发一款无头浏览器,它不适合所有人的需求,否则它有点像黑客:

您可以“假定”将一些参数传入Chrome,具体来说:
——无启动窗口

请注意,对于某些浏览器,尤其是Internet Explorer,如果没有集中运行它,将损害您的测试


您还可以稍微修改一下,以在窗口打开后隐藏它。

在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窗口服务器,如Xvfb,并将显示环境变量指向它:


如果您在Python中使用Selenium web驱动程序,那么可以使用PyVirtualDisplay,这是一种用于Xvfb和Xephyr的Python包装

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

sudo apt-get install xvfb
然后从以下位置安装PyVirtualDisplay:

Python中带有PyVirtualDisplay的无头模式下的Selenium脚本示例:

#/usr/bin/env python
从pyvirtualdisplay导入显示
从selenium导入webdriver
显示=显示(可见=0,大小=(800600))
display.start()
#现在Firefox将在虚拟显示器上运行。
#您将看不到浏览器。
browser=webdriver.Firefox()
browser.get('http://www.google.com')
打印浏览器.title
browser.quit()
display.stop()
编辑

最初的答案发布于2014年,现在我们正处于2018年的关键时刻。和其他东西一样,浏览器也有了进步。Chrome现在有一个完全无头的版本,无需使用任何第三方库来隐藏UI窗口。示例代码如下所示:

从selenium导入webdriver
从selenium.webdriver.chrome.options导入选项
CHROME_PATH='/usr/bin/google CHROME'
CHROMEDRIVER_PATH='/usr/bin/CHROMEDRIVER'
窗口大小=“19201080”
chrome_options=options()
chrome\u选项。添加\u参数(“--headless”)
chrome\u选项。添加参数(“--window size=%s”%window\u size)
chrome\u options.binary\u location=chrome\u路径
driver=webdriver.Chrome(可执行文件路径=CHROMEDRIVER路径,
chrome\u选项=chrome\u选项
)
驱动程序。获取(“https://www.google.com")
获取屏幕截图作为文件(“capture.png”)
驱动程序关闭()
我建议使用。有关更多信息,请访问

据我所知,PhantomJS只适用于Firefox

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

我把我的放在里面:普通的phantomjs.exe

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

browser = webdriver.Firefox()
差不多

import os
path2phantom = os.getcwd() + "\common\Library\phantomjs.exe"
browser = webdriver.PhantomJS(path2phantom)
通往幻影的道路可能不同。。。随意更改:)


这项技术对我有效,我很肯定它也会对你有效;)

以下是一个适合我的.NET解决方案:

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')
下载PhantomJS

从下载文件夹中的bin文件夹复制.exe文件,并将其粘贴到Visual Studio项目的bin debug/release文件夹

使用

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窗口不同,因为最后一个不会启动窗口。它用于托管后台应用程序,如图所示

将标志传递给Selenium webdriver(ChromeDriver)的Java代码:


对于在没有任何浏览器的情况下运行,可以在无头模式下运行

我向您展示了一个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)

我也在谷歌官方网站上为您添加了更多关于这方面的信息,因为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%

PhantomJSDriver

using (IWebDriver driver = new PhantomJSDriver())
{
     // The rest of your test
}
Mozilla 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获得+

Mozilla Firefox的无头模式比UI版本的性能高3.68%。这是令人失望的,因为Chrome的无头模式比UI模式获得了超过30%的时间。另一款无头驱动程序PhantomJS的性能比Chrome的无头模式好34.92%。令人惊讶的是,Edge浏览器胜过了所有浏览器

var options = new FirefoxOptions();
options.AddArguments("--headless");
{
    // The rest of your test
}
注意:PhantomJS不再维护


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

        ChromeOptions chromeOptions = new ChromeOptions();
        chromeOptions.setHeadless(true);
        WebDriver driver = new ChromeDriver(chromeOptions);
如果您使用的是Ubuntu(Gnome),一个简单的解决方法是安装Gnome扩展自动移动窗口:


然后将浏览器(如Chrome)设置为另一个工作空间(如工作空间2)。浏览器将在其他工作区中无声运行,不再打扰您。您仍然可以在工作区中不受任何干扰地使用Chrome。

我的chromedriver在使用Python和选项时遇到了相同的问题。添加参数(“headless”)不起作用
opt = webdriver.ChromeOptions()
opt.arguments.append("headless")
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')
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')
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(...)
...
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)