Selenium Webdriver可以在后台静默打开浏览器窗口吗?

kev*_*ler 139 webdriver selenium-grid selenium-webdriver

我有一个运行许多测试的selenium测试套件,在每个新测试中,它打开了我打开的任何其他窗口顶部的浏览器窗口.在当地环境中工作时非常震动.有什么办法告诉selenium或操作系统(MAC)在后台打开窗口?

Ami*_*tad 155

如果您在Python中使用Selenium Web驱动程序,则可以使用PyVirtualDisplay,它是Xvfb和Xephyr的Python包装器.

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

sudo apt-get install xvfb
Run Code Online (Sandbox Code Playgroud)

然后从Pypi安装PyVirtualDisplay:

pip install pyvirtualdisplay
Run Code Online (Sandbox Code Playgroud)

使用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()
Run Code Online (Sandbox Code Playgroud)

编辑 最初的答案发布于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()
Run Code Online (Sandbox Code Playgroud)

  • 它适用于Mac OSX吗? (7认同)
  • 不推荐使用 chrome_options,现在只是选项 (2认同)

Arr*_*ran 59

有几种方法,但它不是一个简单的"设置配置值".除非你投资一个不适合每个人需求的无头浏览器,否则它有点像黑客:

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

是否可以在Selenium RC中隐藏浏览器?

你可以'推测',将一些参数传递给Chrome,具体来说: --no-startup-window

请注意,对于某些浏览器,尤其是IE,它会损害您的测试,使其无法在焦点上运行.

您还可以使用AutoIT进行一些操作,以便在窗口打开后隐藏它.

  • 事实上,使用“--headless”而不是“--no-startup-window”,我已经确认它适用于 Mac 和 Chrome v80 (11认同)
  • "--no-startup-window"现已弃用 (4认同)

小智 35

Chrome 57有一个传递--headless标志的选项,这使得窗口不可见.

此标志与--no-startup-window不同,因为最后一个不启动窗口.它用于托管后台应用程序,如此页面所示.

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

ChromeOptions options = new ChromeOptions();
options.addArguments("--headless");
ChromeDriver chromeDriver = new ChromeDriver(options);
Run Code Online (Sandbox Code Playgroud)


小智 15

从Chrome 57开始,你就有了无头的争论:

var options = new ChromeOptions();
options.AddArguments("headless");
using (IWebDriver driver = new ChromeDriver(options))
{
    // the rest of your test
}
Run Code Online (Sandbox Code Playgroud)

Chrome的无头模式比UI版本好30.97%.另一款无头驱动程序PhantomJS比Chrome的无头模式提供了34.92%的优势.

PhantomJSDriver

using (IWebDriver driver = new PhantomJSDriver())
{
     // the rest of your test
}
Run Code Online (Sandbox Code Playgroud)

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
}
Run Code Online (Sandbox Code Playgroud)

这可以从Firefox 57+获得

Mozilla Firefox的无头模式比UI版本好3.68%.这是令人失望的,因为Chrome的无头模式比UI用户的时间要好30%.另一款无头驱动程序PhantomJS比Chrome的无头模式提供了34.92%的优势.令我惊讶的是,Edge浏览器击败了所有这些.

注意:PhantomJS不再维护了!


Pou*_*sel 13

我在 Windows 中为 Firefox 使用了此代码并得到了答案(参考此处):

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(...)
...
Run Code Online (Sandbox Code Playgroud)

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

  • 我为其他会看到这篇文章的人回答 (9认同)
  • 感谢您为我们提供 Firefox 替代方案 (3认同)
  • 也适用于镀铬! (3认同)
  • 奇迹般有效! (2认同)

小智 12

要在没有任何浏览器的情况下运行,您可以在无头模式下运行它.

我现在向您展示一个适用于我的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)
Run Code Online (Sandbox Code Playgroud)

我还在Google官方网站上为您提供了更多相关信息https://developers.google.com/web/updates/2017/04/headless-chrome


Ayo*_*oub 8

我建议您使用Phantom Js获取更多信息,以便访问Phantom官方网站

据我所知,PhantomJS仅适用于Firefox ..

下载PhantomJs.exe后你需要导入你的项目,如下图所示,Phantomjs内部常见 >> Library >> phantomjs.exe 在此输入图像描述

现在,您必须在Selenium代码中更改线条

browser = webdriver.Firefox()
Run Code Online (Sandbox Code Playgroud)

喜欢的东西

import os
path2phantom = os.getcwd() + "\common\Library\phantomjs.exe"
browser = webdriver.PhantomJS(path2phantom)
Run Code Online (Sandbox Code Playgroud)

phantomjs的路径可能会有所不同......随你改变:)

就是这样,它对我有用.干杯肯定会为你工作


Pio*_*ski 5

在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)
Run Code Online (Sandbox Code Playgroud)

例:

hider=HideFox('firefox.exe')  #can be anything, eq: phantomjs.exe, notepad.exe ...
#To hide the window
hider.hide()
#To show again
hider.show()
Run Code Online (Sandbox Code Playgroud)

但是,此解决方案存在一个问题-使用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+"';")
Run Code Online (Sandbox Code Playgroud)


归档时间:

查看次数:

184971 次

最近记录:

6 年,2 月 前