Java 类org.openqa.selenium.WebDriver 实例源码

项目:Spring-Security-Third-Edition    文件:SeleniumTestUtilities.java   
public static WebDriver getFirefoxDriver()
            throws Exception
    {
        baseDir = new File(".").getPath();
        System.out.println("******** " + baseDir);

        String path = "src/test/resources/geckodriver";
        System.out.println("******** " + path);
        System.setProperty("webdriver.gecko.driver", path);

        DesiredCapabilities capabilities =  DesiredCapabilities.firefox();
        capabilities.setCapability("marionette", true);
        capabilities.setCapability("networkConnectionEnabled", true);
        capabilities.setCapability("browserConnectionEnabled", true);


        WebDriver driver = new RemoteWebDriver(
                new URL("http://localhost:4444"),
                capabilities);

//      WebDriver driver = new MarionetteDriver(capabilities);

        return driver;
    }
项目:Cognizant-Intelligent-Test-Scripter    文件:WebDriverFactory.java   
private static WebDriver checkEmulators(String browserName, DesiredCapabilities caps, ProjectSettings settings,
        Boolean isGrid, String remoteUrl) {
    Emulator emulator = settings.getEmulators().getEmulator(browserName);
    if (emulator != null) {
        switch (emulator.getType()) {
            case "Duplicate":
                return create(emulator.getDriver(), caps, settings, isGrid, remoteUrl);
            case "Emulator":
                if (emulator.getDriver().equals("Chrome")) {
                    return checkAndSetSize(
                            create(emulator.getDriver(), getChromeUAECaps(caps, emulator), settings, isGrid, remoteUrl),
                            emulator.getSize());
                } else {
                    return checkAndSetSize(
                            create(emulator.getDriver(), getFFUAECaps(caps, emulator), settings, isGrid, remoteUrl),
                            emulator.getSize());
                }
            case "Chrome Emulator":
                return create("Chrome", getChromeEmulatorCaps(caps, emulator.getDriver()), settings, isGrid, remoteUrl);
            case "Remote URL": {
                return createRemoteDriver(emulator.getRemoteUrl(), caps, settings.getDriverSettings().useProxy(), settings.getDriverSettings());
            }
        }
    }
    return null;
}
项目:Selenium-Foundation    文件:ComponentContainerTest.java   
/**
 * Create mocked {@link WebElement} object.
 * 
 * @param type element type
 * @param value element value
 * @param isCheckbox 'true' is checkbox is desired; otherwise 'false'
 * @return mocked WebElement object
 */
private static WebElement mockElement(String type, String value, boolean isCheckbox) {
    WebElement element = mock(WebElement.class, withSettings().extraInterfaces(WrapsDriver.class));
    when(element.getTagName()).thenReturn(type);
    if (isCheckbox) {
        when(element.getAttribute("type")).thenReturn("checkbox");
        when(element.getAttribute("value")).thenReturn("isSelected: " + value);
        when(element.isSelected()).thenReturn(Boolean.parseBoolean(value));
    } else {
        when(element.getAttribute("type")).thenReturn("text");
        when(element.getAttribute("value")).thenReturn(value);
        when(element.isSelected()).thenReturn(false);
    }

    WebDriver driver = mockDriver();
    when(((WrapsDriver) element).getWrappedDriver()).thenReturn(driver);
    return element;
}
项目:selenium-camp-17    文件:Java7WebDriverFactory.java   
public static WebDriver getDriverUsingIf(DesiredCapabilities desiredCapabilities) {
    if (desiredCapabilities == null) {
        throw new IllegalStateException("DesiredCapabilities are missing!");
    }

    final String browser = desiredCapabilities.getBrowserName();

    if (CHROME.equalsIgnoreCase(browser)) {
        return new ChromeDriver(desiredCapabilities);
    } else if (FIREFOX.equalsIgnoreCase(browser)) {
        return new FirefoxDriver(desiredCapabilities);
    } else if (browser.isEmpty()) {
        throw new IllegalStateException("'browser' capability is missing!");
    }

    throw new IllegalArgumentException(desiredCapabilities.getBrowserName() + " browser is not supported!");
}
项目:selenium-toys    文件:AbstractDownloadingWebDriverFactory.java   
@Override
public WebDriver create(final Map<String, Object> options) {
  new Initialization(() -> {
    beforeInitialization(options);

    final File workDirectory = getWorkDirectory(options);
    final String expectedVersion = (String) options.get(EXPECTED_VERSION);
    final boolean forceUpdate = Boolean.parseBoolean((String) options.get(FORCE_UPDATE));
    final File webDriverExecutable =
        new DownloadWebDriverExecutable(workDirectory, getWebDriverExecutableFromWorkDirectory,
            getLatestVersion, downloadExpectedVersion).get(expectedVersion, forceUpdate);
    new SystemPropertyWebDriverExecutableSetup(systemPropertyForExecutable, webDriverExecutable)
        .setup();
    webDriver = instantiateWebDriver(options);
    new WebDriverShutdownHook(webDriver).install();

    afterInitialization(options);
  }).initialize();
  return webDriver;
}
项目:teasy    文件:TeasyElementFinder.java   
private <T extends TeasyElement> List<T> getElements(By locator, Function<WebDriver, List<WebElement>> condition, TeasyElementType type) {
    List<WebElement> webElements;
    try {
        webElements = fluentWait.waitFor(condition);
    } catch (AssertionError ignoredToReturnEmptyList) {
        return new ArrayList<>();
    }
    if (webElements == null) {
        return new ArrayList<>();
    }
    if (context == null) {
        return wrapList(webElements, locator, type);
    } else {
        return wrapList(context, webElements, locator, type);
    }
}
项目:crawler    文件:WebDriverManager.java   
public void load(SeleniumAction... actions){
    WebDriver driver=null;
    try {
        driver=webDriverPool.get();
        WebDriver.Options manage = driver.manage();
        manage.window().maximize();
        for(SeleniumAction action:actions){
            action.execute(driver);
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
        log.error("",e);
    }finally{
        if(driver!=null){
            webDriverPool.returnToPool(driver);
        }
    }
}
项目:Actitime-Framework    文件:ReportNGReport.java   
/**
 * This method captures a screenshot
 **/
public static void captureScreenshot(WebDriver driver, String screenshotName) {
    try {
        TakesScreenshot ts = (TakesScreenshot) driver;
        File source = ts.getScreenshotAs(OutputType.FILE);
        FileUtils.copyFile(source, new File(dirPath + "/ " + screenshotName
                + "_" + strDateStamp

                + ".png"));
        String ESCAPE_PROPERTY = "org.uncommons.reportng.escape-output";
        System.setProperty(ESCAPE_PROPERTY, "false");
        URL path = new File(dirPath + "/ " + screenshotName + "_"
                + strDateStamp + ".png").toURI().toURL();
        String test = "<a href=" + path + "> click to open screenshot of "
                + screenshotName + "</a>";
        Reporter.log(screenshotName + test + "<br>");
        Reporter.log("<br>");
    }

    catch (Exception e) {
        System.out.println("Exception while taking screenshot "
                + e.getMessage());
    }
}
项目:Cognizant-Intelligent-Test-Scripter    文件:CommonMethods.java   
private boolean isAlertPresent(WebDriver Driver) {
    try {
        Driver.switchTo().alert();
        return true;
    } catch (NoAlertPresentException e) {
        Logger.getLogger(this.getClass().getName()).log(Level.OFF, e.getMessage(), e);
        return false;
    }
}
项目:teasy    文件:ElementsHaveText.java   
@Nullable
@Override
public Boolean apply(@Nullable WebDriver webDriver) {
    List<String> actualTexts = new ArrayList<>();
    errorElements = new ArrayList<>();
    boolean isCorrect = true;
    for (TeasyElement el : elements) {
        actualTexts.add(el.getText());
        if (!text.equals(el.getText())) {
            isCorrect = false;
            errorElements.add(el);
        }
    }
    return isCorrect;
}
项目:webdriver-supplier    文件:MockWDFactory.java   
@Override
public WebDriver createDriver(final Browser browser, final XmlConfig config) {
    final RemoteWebDriver driver = mock(RemoteWebDriver.class);
    when(driver.getScreenshotAs(OutputType.BYTES)).thenReturn(new byte[]{1, 2, 3});
    doReturn(new SessionId(randomAlphanumeric(14))).when(driver).getSessionId();
    return driver;
}
项目:Spring-Security-Third-Edition    文件:SeleniumTestUtilities.java   
public static WebDriver getChromeDriver()
{
       String path = "src/test/resources/chromedriver";
    System.setProperty("webdriver.chrome.driver", path);

    DesiredCapabilities capabilities = DesiredCapabilities.chrome();
       capabilities.setCapability("networkConnectionEnabled", true);
       capabilities.setCapability("browserConnectionEnabled", true);

       return new ChromeDriver(capabilities);
}
项目:dashboard1b    文件:SeleniumUtils.java   
static public void esperaCargaPaginaNoTexto(WebDriver driver, String texto, int timeout)
{
    Boolean resultado = 
            (new WebDriverWait(driver, timeout)).until(ExpectedConditions.invisibilityOfElementLocated(By.xpath("//*[contains(text(),'" + texto + "')]")));

    assertTrue(resultado);  
}
项目:Selenium-Foundation    文件:ScreenshotUtils.java   
/**
 * Determine if the specified driver is capable of taking screenshots.
 * 
 * @param optDriver optional web driver object
 * @param logger SLF4J logger object
 * @return 'true' if driver can take screenshots; otherwise 'false
 */
public static boolean canGetArtifact(Optional<WebDriver> optDriver, Logger logger) {
    if (optDriver.isPresent()) {
        WebDriver driver = optDriver.get();
        if (driver instanceof TakesScreenshot) {
            return true;
        } else {
            String message = "This driver is not capable of taking a screenshot.  If a screenshot is desired, use"
                    + " a WebDriver implementation that supports screenshots. For more information, see https://"
                    + "seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/TakesScreenshot.html";
            logger.warn(message);
        }
    }
    return false;
}
项目:willtest    文件:EventListenerExample.java   
@Test
public void testEventListenerWithError() {
    WebDriver webDriver = rule.getWebDriver();
    webDriver.get("https://github.com");
    WebElement searchInput = webDriver.findElement(By.cssSelector(".header-search-input"));
    searchInput.sendKeys("will", "test");
    searchInput.sendKeys(Keys.ENTER);
    String searchKeyword = webDriver.findElement(By.cssSelector(".header-search-input")).getAttribute("value");
    assertThat(searchKeyword, is("foooooo"));
}
项目:selenium-components    文件:AbstractSeleniumPage.java   
public String getScreenshot()
{
    WebDriver driver = environment.getDriver();

    if (driver instanceof TakesScreenshot)
    {
        return ((TakesScreenshot) driver).getScreenshotAs(OutputType.BASE64);
    }

    return null;
}
项目:givemeadriver    文件:WebDriverContainerTest.java   
@Test
public void cleanupThreadClosesTheDriver() {
    // given
    container.WEB_DRIVER = mock(WebDriver.class);
    WebDriverContainer.WebDriverCleanupThread cleanupThread = container.new WebDriverCleanupThread();
    // when
    cleanupThread.run();
    // then
    assertThat(container.WEB_DRIVER).isNull();

}
项目:Spring-Security-Third-Edition    文件:SeleniumTestUtilities.java   
public static WebDriver getChromeDriver(String pathToChromeExecutable)
{
    String path = System.getProperty("user.dir") + "\\Drivers\\chromedriver.exe";
    System.setProperty("webdriver.chrome.driver",path);

    Map<String, Object> chromeOptions = new HashMap<String, Object>();
    chromeOptions.put("binary", pathToChromeExecutable);
    DesiredCapabilities capabilities = DesiredCapabilities.chrome();
    capabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions);

    return new ChromeDriver(capabilities);
}
项目:participationSystem3b    文件:SeleniumUtils.java   
static public List<WebElement> EsperaCargaPagina(WebDriver driver, String criterio, String id, int timeout)
{
    String busqueda;
    if (criterio.equals("id")) busqueda = "//*[contains(@id,'" + id + "')]";
    else if (criterio.equals("class")) busqueda = "//*[contains(@class,'" + id + "')]";
    else busqueda = "//*[contains(text(),'" + id + "')]";
    return EsperaCargaPaginaxpath(driver, busqueda, timeout);
}
项目:selenium-toys    文件:TypeTest.java   
@Test
public void onTest() {
  final WebDriver webDriver = Mockito.mock(WebDriver.class);
  final WebElement webElement = Mockito.mock(WebElement.class);

  final Type type = new Type(webDriver, "text", () -> {});
  final By byId = By.id("id");
  Mockito.when(webDriver.findElement(byId)).thenReturn(webElement);
  type.on(byId);
  Mockito.verify(webElement).sendKeys("text");
}
项目:AutomationFrameworkTPG    文件:WebDriverInstance.java   
public WebDriver getDriver() {
    if (driver == null) {
        DriverProperties driverProperties = getDriverProperties();
        driver = driverProperties.setDriver(driverProperties.getAppURL());
    }
    return driver;
}
项目:POM_HYBRID_FRAMEOWRK    文件:WebButton.java   
/**
 * Web button click.
 *
 * @param driver the driver
 * @param logger the logger
 * @param element the element
 */
public static void webButtonClick(WebDriver driver, ExtentTest logger, WebElement element) {
    try {
        if (element != null && element.isEnabled()) {
            element.click();
        }
    } catch (Exception e) {
        }
}
项目:participationSystem3b    文件:SeleniumUtils.java   
static public void ClickSubopcionMenuHover(WebDriver driver, String submenu, String opcionclick)
{
    //Pasamos el raton por el submenu de Gestion de alumnos para
    //que aparezca el menu desplegable
    Actions builder = new Actions(driver);
    WebElement hoverElement = driver.findElement(By.id(submenu));
    builder.moveToElement(hoverElement).perform();      
    //Pinchamos la opcion opcionclick
    By locator = By.id(opcionclick);
    driver.findElement(locator).click();            
}
项目:satisfy    文件:SatisfyBaseStepListener.java   
public SatisfyBaseStepListener(final Class<? extends WebDriver> driverClass,
                               final File outputDirectory,
                               final Configuration configuration) {
    this(outputDirectory);
    this.driver = getProxyFactory().proxyFor(driverClass);
    this.configuration = configuration;
}
项目:Cognizant-Intelligent-Test-Scripter    文件:WebDriverFactory.java   
private static WebDriver checkAndSetSize(WebDriver driver, String size) {
    if (driver != null) {
        if (size.matches("[0-9]+ x [0-9]+")) {
            int w = Integer.valueOf(size.split("x")[0].trim());
            int h = Integer.valueOf(size.split("x")[1].trim());
            driver.manage().window().setSize(new Dimension(w, h));
        }
    }
    return driver;
}
项目:Java-Data-Science-Cookbook    文件:WebdataExtractionSelenium.java   
public static void main(String[] args) {
       WebDriver driver = new FirefoxDriver();
       driver.get("http://cogenglab.csd.uwo.ca/rushdi.htm");

       WebElement webElement = driver.findElement(By.xpath("//*[@id='content']"));
    System.out.println(webElement.getText());

}
项目:selenium-jupiter    文件:DriverHandler.java   
public String getName() {
    String name = "";
    Optional<Method> testMethod = context.getTestMethod();
    if (testMethod.isPresent()) {
        name = testMethod.get().getName();
    }
    name += "_" + parameter.getName() + "_"
            + object.getClass().getSimpleName();
    if (WebDriver.class.isAssignableFrom(object.getClass())) {
        name += "_" + ((RemoteWebDriver) object).getSessionId();
    }
    return name;
}
项目:crawler    文件:PhantomjsWebDriverPool.java   
public void returnToPool(WebDriver webDriver) {
    if (shutdowned.get()) {
        webDriver.quit();
        webDriver = null;
    } else {
        Set<String> handles = webDriver.getWindowHandles();
        if (handles.size() > 1) {
            int index = 0;
            for (String handle : handles) {
                if (index == 0) {
                    index++;
                    continue;
                }
                WindowUtil.changeWindowTo(webDriver, handle);
                webDriver.close();
                index++;
            }
        }
        synchronized (shutdowned) {
            if(!shutdowned.get()){
                innerQueue.add(webDriver);
            }else{
                webDriver.quit();
                webDriver = null;
            }
        }
    }
}
项目:KITE    文件:NoAdapterTestTest.java   
public void tearDown() throws Exception {
  // Close all the browsers
  for (WebDriver webDriver : this.webDriverList)
    try {
      webDriver.quit();
    } catch (Exception e) {
      e.printStackTrace();
    }
}
项目:selenium-jupiter    文件:TemplateTwoBrowsersTest.java   
@TestTemplate
void templateTest(WebDriver driver1, WebDriver driver2) {
    driver1.get("https://bonigarcia.github.io/selenium-jupiter/");
    driver2.get("https://bonigarcia.github.io/selenium-jupiter/");
    assertThat(driver1.getTitle(),
            containsString("A JUnit 5 extension for Selenium WebDriver"));
    assertThat(driver2.getTitle(),
            containsString("A JUnit 5 extension for Selenium WebDriver"));
}
项目:autotest    文件:WebTestBase.java   
/**
 * 切换到新窗口
 *
 * @param driver
 */
public void switchToNewWindow(WebDriver driver) {
    String[] handles = new String[driver.getWindowHandles().size()];
    driver.getWindowHandles().toArray(handles);// 把list转换成数组
    int i = handles.length;
    driver.switchTo().window(handles[i - 1]);// 切换窗口
}
项目:Selenium-Foundation    文件:ScreenshotUtils.java   
/**
 * Produce page source from the specified driver.
 * 
 * @param optDriver optional web driver object
 * @param reason impetus for capture request; may be 'null'
 * @param logger SLF4J logger object
 * @return page source; if capture fails, an empty string is returned
 */
public static byte[] getArtifact(Optional<WebDriver> optDriver, Throwable reason, Logger logger) {
    if (canGetArtifact(optDriver, logger)) {
        try {
            WebDriver driver = optDriver.get();
            return ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
        } catch (WebDriverException e) {
            logger.warn("The driver is capable of taking a screenshot, but it failed.", e);
        }
    }
    return new byte[0];
}
项目:Cognizant-Intelligent-Test-Scripter    文件:GalenWrapper.java   
public synchronized static File takeScreenShot(WebDriver Driver) {
    try {
        return GalenUtils.makeFullScreenshot(Driver);
    } catch (IOException | InterruptedException ex) {
        Logger.getLogger(GalenWrapper.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}
项目:bootstrap    文件:AbstractSequentialSeleniumTest.java   
/**
 * Sequentially run the desired capabilities.
 */
protected void runSequential() { // NOPMD -- thread
    final WebDriver[] drivers = new WebDriver[repeatedCapabilities.length];
    final boolean[] success = new boolean[repeatedCapabilities.length];
    for (int index = 0; index < repeatedCapabilities.length; index++) {
        final int driverIndex = index;
        final DesiredCapabilities capability = repeatedCapabilities[driverIndex];
        success[driverIndex] = false;
        runSequentialIndex(drivers, success, driverIndex, capability);
    }

    final List<String> faillures = checkResults(success);
    Assert.assertTrue("All browsers test failed", faillures.size() != success.length);
    Assert.assertEquals("Some browsers test failed", 0, faillures.size());
}
项目:redirector    文件:FlavorRulesTemplatesShowPage.java   
public FlavorRulesTemplatesShowPage(WebDriver webDriver) {
    super(webDriver);
}
项目:Selenium-Foundation    文件:RobustElementFactory.java   
/**
 * Get robust web element factory for this context.
 * 
 * @param context target context
 * @return robust web element factory
 */
private static synchronized InstanceCreator getCreator(WrapsContext context) {
    WebDriver driver = context.getWrappedDriver();
    String driverName = driver.getClass().getName();
    if (creatorMap.containsKey(driverName)) {
        return creatorMap.get(driverName);
    }

    WebElement reference = driver.findElement(By.tagName("*"));
    Class<? extends WebElement> refClass = reference.getClass();

    Class<? extends WebElement> wrapperClass = new ByteBuddy()
                    .subclass(refClass)
                    .name(refClass.getPackage().getName() + ".Robust" + refClass.getSimpleName())
                    .method(not(isDeclaredBy(Object.class)))
                    .intercept(MethodDelegation.withEmptyConfiguration()
                            .withBinders(TargetMethodAnnotationDrivenBinder.ParameterBinder.DEFAULTS)
                            .withResolvers(MethodNameEqualityResolver.INSTANCE, BindingPriority.Resolver.INSTANCE)
                            .filter(not(isDeclaredBy(Object.class)))
                            .toField("interceptor"))
                    .implement(RobustWebElement.class)
                    .defineField("interceptor", RobustElementWrapper.class, Visibility.PRIVATE)
                    .implement(InterceptionAccessor.class).intercept(FieldAccessor.ofBeanProperty())
                    .make()
                    .load(refClass.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
                    .getLoaded();

    InstanceCreator creator;

    try {
        creator = new ByteBuddy()
                        .subclass(InstanceCreator.class)
                        .method(not(isDeclaredBy(Object.class)))
                        .intercept(MethodDelegation.toConstructor(wrapperClass))
                        .make()
                        .load(wrapperClass.getClassLoader())
                        .getLoaded().newInstance();
    } catch (InstantiationException | IllegalAccessException e) {
        throw UncheckedThrow.throwUnchecked(e);
    }

    creatorMap.put(driverName, creator);
    return creator;
}
项目:msa-cucumber-appium    文件:MobileApp.java   
public static WebDriver getDriver() {
    return driver.get();
}
项目:teasy    文件:VisibleElementWaitFor.java   
public VisibleElementWaitFor(TeasyElement element, TeasyFluentWait<WebDriver> fluentWait) {
    this.element = element;
    this.fluentWait = fluentWait;
}
项目:Selenium-Foundation    文件:ScreenshotArtifact.java   
/**
 * {@inheritDoc}
 */
@Override
public byte[] getArtifact(ITestResult result) {
    Optional<WebDriver> optDriver = DriverManager.nabDriver(result.getInstance());
    return ScreenshotUtils.getArtifact(optDriver, result.getThrowable(), LOGGER);
}
项目:Java_Good    文件:SessionHelper.java   
public SessionHelper(WebDriver wd) {
    super(wd);
}