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


当前回答

我在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模式下运行。

我给你们看一个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上给大家补充了更多的信息

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

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

利用它……

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

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

实现这一点的一种方法是在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();
    }
}

如果你正在使用谷歌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')