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


当前回答

要在没有浏览器的情况下运行,可以在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上给大家补充了更多的信息

其他回答

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

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

and

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

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

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

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

要在没有浏览器的情况下运行,可以在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上给大家补充了更多的信息

如果你使用的是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")

在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 + "';")