如何使用Selenium WD为不同的浏览器类型打开隐身/私人窗口?

时间:2015-10-19 21:16:24

标签: java browser selenium-webdriver

我想在 私人窗口 隐身窗口 中测试我的测试用例。

如何在各种浏览器中执行相同操作:

  • firefox(首选)
  • chrome(首选)
  • IE
  • safari
  • 歌剧

如何实现?

9 个答案:

答案 0 :(得分:17)

  • 铬:

    Parallel.ForEach
  • 的FireFox:

    private void GenerateRecords(JobRequest request)
    {
        Parallel.For(0, daysInRange, day =>
        {
            foreach (var coreId in request.CoreIds)
            {
                for (var i = 0; i < request.AgentsCount; i++)
                {
                    var agentId = Guid.NewGuid();
    
                    for (var copiesDone = 0; copiesDone < request.CopiesToMake; copiesDone++)
                    {
                        foreach (var jobInfoRecord in request.Jobs)
                        {
                            foreach (var status in request.Statuses)
                            {
                                //DoSomeWork();
                            }
                        }
                    }
                }
            }
        });
    }
    
  • Internet Explorer:

    <div ng-controller="MyCtrl">
    selected val={{}}
     <select ng-model="selectedOption" ng-mouseup="showSelected()">
        <option value="">Select Option</option>
        <option value="option-1">Option 1</option>
        <option value="option-2">Option 2</option>
    </select>
    </div>
    
    
    
    function MyCtrl($scope) {
        $scope.open=false;
        $scope.showSelected = function () {
        if($scope.open) {
        // here s your code for select
            console.log('Selected');
        }
        $scope.open=!$scope.open;
        }
    }
    
  • 歌剧:

    DesiredCapabilities capabilities = DesiredCapabilities.chrome();
    ChromeOptions options = new ChromeOptions();
    options.addArguments("incognito");
    capabilities.setCapability(ChromeOptions.CAPABILITY, options);
    

答案 1 :(得分:9)

在chrome中,您可以尝试在选项中使用-incognito命令行开关,不确定自动化扩展是否存在问题,但值得一试。

ChromeOptions options = new ChromeOptions();
options.addArguments("incognito");

对于FireFox,配置文件中的特殊标志可用于此目的

FirefoxProfile firefoxProfile = new FirefoxProfile();    
firefoxProfile.setPreference("browser.private.browsing.autostart",true);

对于IE

setCapability(InternetExplorerDriver.IE_SWITCHES, "-private");

答案 2 :(得分:0)

在页面上找到body元素,然后为所需的浏览器触发Key Chord。在下面的示例中,我尝试将浏览器抽象为枚举概述 newTab newWindow newIncognitoWindow 的行为的枚举。我制作了内容FF,IE,Chrome,Safari和Opera;但是,由于我缺乏知识,它们可能无法完全实施。

  /**
     * Enumeration quantifying some common keystrokes for Browser Interactions.
     * 
     * @see "http://stackoverflow.com/questions/33224070/how-to-open-incognito-private-window-through-selenium-java"
     * @author http://stackoverflow.com/users/5407189/jeremiah
     * @since Oct 19, 2015
     *
     */
    public static enum KeystrokeSupport {
        CHROME,
        FIREFOX {
            @Override
            protected CharSequence getNewIncognitoWindowCommand() {
                return Keys.chord(Keys.CONTROL, Keys.SHIFT, "p");
            }
        },
        IE {
            @Override
            protected CharSequence getNewIncognitoWindowCommand() {
                return Keys.chord(Keys.CONTROL, Keys.SHIFT, "p");
            }
        },
        SAFARI {
            @Override
            protected CharSequence getNewTabCommand() {
                throw new UnsupportedOperationException("Author does not know this keystroke");
            }

            @Override
            protected CharSequence getNewWindowCommand() {
                throw new UnsupportedOperationException("Author does not know this keystroke");
            }

            @Override
            protected CharSequence getNewIncognitoWindowCommand() {
                throw new UnsupportedOperationException("Author does not know this keystroke");
            }
        },
        OPERA {
            @Override
            protected CharSequence getNewIncognitoWindowCommand() {
                throw new UnsupportedOperationException("Author does not know this keystroke");
            }
        };

        public final void newTab(WebDriver driver) {
            WebElement target = getKeystrokeTarget(driver);
            target.sendKeys(getNewTabCommand());
        }

        public final void newWindow(WebDriver driver) {
            WebElement target = getKeystrokeTarget(driver);
            target.sendKeys(getNewWindowCommand());
        }

        public final void newIncognitoWindow(WebDriver driver) {
            WebElement target = getKeystrokeTarget(driver);
            target.sendKeys(getNewIncognitoWindowCommand());
        }

        protected CharSequence getNewTabCommand() {
            return Keys.chord(Keys.CONTROL, "t");
        }

        protected CharSequence getNewWindowCommand() {
            return Keys.chord(Keys.CONTROL, "n");
        }

        protected CharSequence getNewIncognitoWindowCommand() {
            return Keys.chord(Keys.CONTROL, Keys.SHIFT, "t");
        }

        protected final WebElement getKeystrokeTarget(WebDriver driver) {
            WebDriverWait wait = new WebDriverWait(driver, 10);
            return wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("body")));
        }

    }

然后,我们可以提供参数化测试,该测试将贯穿每个配置并执行可视化验证的行为。您可能希望在测试中添加您想要的任何断言。

package stackoverflow.proof.selenium;

import java.util.Collection;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;


import com.google.common.base.Supplier;
import com.google.common.collect.Lists;



/**
 * Test to try out some various browser keystrokes and try to get the environment to do what we want.
 * 
 * @see "http://stackoverflow.com/questions/33224070/how-to-open-incognito-private-window-through-selenium-java"
 * @author http://stackoverflow.com/users/5407189/jeremiah
 * @since Oct 19, 2015
 *
 */
@RunWith(Parameterized.class)
public class KeyStrokeTests {


    @Parameters(name="{0}")
    public static Collection<Object[]> buildTestParams() {
        Collection<Object[]> params = Lists.newArrayList();
        Supplier<WebDriver> ffS = new Supplier<WebDriver>() {
            public WebDriver get() {
                return new FirefoxDriver();
            }
        };
        params.add(new Object[]{KeystrokeSupport.FIREFOX, ffS});

      /* I'm not currently using these browsers, but this should work with minimal effort.
        Supplier<WebDriver> chrome = new Supplier<WebDriver>() {
            public WebDriver get() {
                return new ChromeDriver();
            }
        };
        Supplier<WebDriver> ie = new Supplier<WebDriver>() {
            public WebDriver get() {
                return new InternetExplorerDriver();
            }
        };
        Supplier<WebDriver> safari = new Supplier<WebDriver>() {
            public WebDriver get() {
                return new SafariDriver();
            }
        };
        Supplier<WebDriver> opera = new Supplier<WebDriver>() {
            public WebDriver get() {
                return new OperaDriver();
            }
        };

        params.add(new Object[]{KeystrokeSupport.CHROME, chrome});
        params.add(new Object[]{KeystrokeSupport.IE, ie});
        params.add(new Object[]{KeystrokeSupport.SAFARI, safari});
        params.add(new Object[]{KeystrokeSupport.OPERA, opera});
        */
        return params;
    }
    Supplier<WebDriver> supplier;
    WebDriver driver;
    KeystrokeSupport support;

    public KeyStrokeTests(KeystrokeSupport support,Supplier<WebDriver> supplier) {
        this.supplier = supplier;
        this.support = support;
    }

    @Before
    public void setup() {
        driver = supplier.get();
        driver.get("http://google.com");
    }

    @Test
    public void testNewTab() {
        support.newTab(driver);
    }
    @Test
    public void testNewIncognitoWindow() {
        support.newIncognitoWindow(driver);
    }

    @Test
    public void testNewWindow() {
        support.newWindow(driver);
    }

    @After
    public void lookAtMe() throws Exception{
        Thread.sleep(5000);    
          for (String handle : driver.getWindowHandles()) {
            driver.switchTo().window(handle);
            driver.close();
        }
    }
  }

最好的运气。

答案 3 :(得分:0)

对于Chrome,请使用此代码以隐身模式打开浏览器:

public WebDriver chromedriver;
ChromeOptions options = new ChromeOptions();
options.addArguments("-incognito");
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
WebDriver chromedriver=new ChromeDriver(capabilities);
chromedriver.get("url");

答案 4 :(得分:0)

public static void OpenBrowser() {
    if (Browser.equals("Chrome")) {
        System.setProperty("webdriver.chrome.driver", "E:\\Workspace\\proj\\chromedriver.exe");
        DesiredCapabilities capabilities = DesiredCapabilities.chrome();
        ChromeOptions options = new ChromeOptions();
        options.addArguments("incognito");
        capabilities.setCapability(ChromeOptions.CAPABILITY, options);
        driver = new ChromeDriver(capabilities);
    } else if (Browser.equals("IE")) {

        DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
        capabilities.setCapability(InternetExplorerDriver.FORCE_CREATE_PROCESS, false);
// if you get this exception "org.openqa.selenium.remote.SessionNotFoundException: " . uncomment the below line and comment the above line
// capabilities.setCapability(InternetExplorerDriver.FORCE_CREATE_PROCESS, true);
        System.setProperty("webdriver.ie.driver", "E:\\Workspace\\proj\\IEDriverServer32.exe");capabilities.setCapability(InternetExplorerDriver.IE_SWITCHES, "-private");
        driver = new InternetExplorerDriver(capabilities);
    } else {
        FirefoxProfile firefoxProfile = new FirefoxProfile();
        firefoxProfile.setPreference("browser.privatebrowsing.autostart", true);
        driver = new FirefoxDriver(firefoxProfile);
    }

答案 5 :(得分:0)

public class gettext {
  static WebDriver driver= null;

  public static void main(String args[]) throws InterruptedException {

    //for private window

    DesiredCapabilities capabilities = DesiredCapabilities.chrome();
    ChromeOptions option = new ChromeOptions();
    option.addArguments("incognito");
    capabilities.setCapability(ChromeOptions.CAPABILITY,option);
    System.setProperty("webdriver.chrome.driver", "D:\\Tools\\chromedriver.exe");       
    driver= new ChromeDriver(capabilities);

    String url = "https://www.google.com/";
    driver.manage().window().maximize();
    driver.get(url);
    driver.manage().timeouts().implicitlyWait(20,TimeUnit.SECONDS);
    gettextdata();
  } 
}

答案 6 :(得分:0)

FirefoxOptions opts = new FirefoxOptions();
opts.addArguments("-private");
FirefoxDrive f = new FirefoxDriver(opts);

这对于硒版本3.14.0和geckodriver-v0.22.0正常工作

答案 7 :(得分:0)

仅在进行以下更新后,我才能在私有模式下运行远程IE:

InternetExplorerOptions options = new InternetExplorerOptions()
                    .ignoreZoomSettings()
                    .useCreateProcessApiToLaunchIe()
                    .addCommandSwitches("-private");

DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
            capabilities.setCapability("se:ieOptions", options);
return new RemoteWebDriver(url, capabilities);

以上所有方法均不适用于RemoteWebDriver。

答案 8 :(得分:0)

如何避免在私有模式下扩展名

对于实际的geckodriver版本,我使用:

    options.addArguments("-private");

工作正常,但出现烦人的通知:“私人模式下的扩展程序”。

我找到了避免这种情况的方法:

    options.addPreference("extensions.allowPrivateBrowsingByDefault",true);

因此,所有扩展程序都将以私人浏览模式运行,而不会在启动时提示