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


当前回答

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

用于测试的假X服务器?

其他回答

下面是一个适合我的。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
}

我建议使用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的路径可能会有所不同……想怎么改就怎么改:)

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

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

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

如果你在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()

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

用于测试的假X服务器?