コード例 #1
0
  // chrome
  public void seleniumChrome(String filePath, String url) throws InterruptedException {
    System.out.println(String.format("Fetching %s...", url));

    // 设置
    System.setProperty(
        "webdriver.chrome.driver",
        "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chromedriver.exe");
    System.out.println("chromedriver opened");

    DesiredCapabilities capabilities = DesiredCapabilities.chrome();
    capabilities.setCapability("chrome.switches", Arrays.asList("--start-maximized"));

    WebDriver driver = new org.openqa.selenium.chrome.ChromeDriver(capabilities);
    driver.manage().timeouts().pageLoadTimeout(20, TimeUnit.SECONDS); // 5秒内没打开,重新加载
    while (true) {
      try {
        driver.get(url);
      } catch (Exception e) {
        driver.quit();
        driver = new ChromeDriver();
        driver.manage().timeouts().pageLoadTimeout(20, TimeUnit.SECONDS);
        continue;
      }
      break;
    }
    // save page
    String html = driver.getPageSource();
    saveHtml(filePath, html);
    System.out.println("save finish...");
    // Close the browser
    Thread.sleep(2000);
    driver.quit();
  }
コード例 #2
0
ファイル: testSample.java プロジェクト: tartek/grid
  @Parameters("browser")
  @Test
  public void testLogin(String browser) throws MalformedURLException, InterruptedException {
    System.out.println(browser);

    DesiredCapabilities cap = null;

    if (browser.equals("firefox")) {
      cap = DesiredCapabilities.firefox();
      cap.setBrowserName("firefox");
      cap.setPlatform(Platform.ANY);
    } else if (browser.equals("chrome")) {
      cap = DesiredCapabilities.chrome();
      cap.setBrowserName("chrome");
      cap.setPlatform(Platform.ANY);
    } else if (browser.equals("iexplorer")) {
      cap = DesiredCapabilities.internetExplorer();
      cap.setBrowserName("iexplore");
      cap.setPlatform(Platform.WINDOWS);
    }
    driver = new RemoteWebDriver(new URL("http://192.168.1.133:5555/wd/hub"), cap);
    // driver.manage().window().maximize();
    driver.get("http://gmail.com");
    driver.findElement(By.id("Email")).sendKeys("Hello");
    Thread.sleep(10000L);
  }
コード例 #3
0
  private ResultItems myDownload(Request request, Spider spider) throws IOException {
    ResultItems resultItems = new ResultItems(request, spider);

    DesiredCapabilities cap = DesiredCapabilities.chrome();
    ChromeOptions co = new ChromeOptions();
    String userAgent = request.getUserAgent();
    co.addArguments("--user-agent=" + userAgent);
    cap.setCapability(ChromeOptions.CAPABILITY, co);

    Proxy myProxy = spider.getProxy(request);
    if (myProxy != null) {
      String proxy = myProxy.getHost() + ":" + myProxy.getPort();
      org.openqa.selenium.Proxy p = new org.openqa.selenium.Proxy();
      p.setHttpProxy(proxy).setFtpProxy(proxy).setSslProxy(proxy);
      cap.setCapability(CapabilityType.PROXY, p);
    }

    WebDriver driver = new ChromeDriver(cap);
    driver.get(request.getUrl());
    // Get the html source of the page
    String pageSource = driver.getPageSource();
    // Close the browser
    driver.quit();
    return resultItems.setResource(Jsoup.parse(pageSource, request.getUrl()));
  }
コード例 #4
0
ファイル: EditUser.java プロジェクト: gaurav1609/QA
  @Parameters({"environment"})
  @BeforeClass
  public void setup(String environment) {

    DesiredCapabilities capabilities = DesiredCapabilities.chrome();
    capabilities.setCapability("chrome.switches", Arrays.asList("--disable-extensions"));
    driver = new ChromeDriver(capabilities);
    driver.manage().window().maximize();
    wait = new WebDriverWait(driver, timeoutSeconds);
    String qa_username = "******";
    String qa_pwd = "Cres@2737";
    String prod_username = "******";
    String prod_pwd = "rajatgupta";
    js = (JavascriptExecutor) driver;
    if (environment.equalsIgnoreCase("QA")) {
      url = "http://mad-learn.com.embr.mobi/";
      driver.navigate().to(url + "Login.aspx");
      waitForElement("btnGo");
      login(qa_username, qa_pwd);
    } else {
      url = "http://platform.mad-learn.com/";
      driver.navigate().to(url + "Login.aspx");
      login(prod_username, prod_pwd);
    }
  }
コード例 #5
0
ファイル: SessionManager.java プロジェクト: 10mdan/automate
  private static DesiredCapabilities getWebCaps(
      Method testMethod, Map<String, Object> customCapabilities) throws Exception {
    // String browserType = ConfigManager.getInstance().getProperty("browser");
    String browserType = "chrome";
    DesiredCapabilities capabilities = null;
    switch (browserType) {
      case "chrome":
        ChromeOptions options = createChromeOptions();
        capabilities = DesiredCapabilities.chrome();
        capabilities.setCapability(ChromeOptions.CAPABILITY, options);
        try {
          String os = null;
          String chromeDriver = "chromedriver";
          if (SystemUtils.IS_OS_MAC_OSX) {
            os = "mac";
          } else if (SystemUtils.IS_OS_LINUX) {
            os = "linux";
            chromeDriver += System.getProperty("sun.arch.data.model");
          } else if (SystemUtils.IS_OS_WINDOWS) {
            os = "windows";
          }
          System.setProperty("webdriver.chrome.driver", "src/resources/chromedriver");
        } catch (Exception e) {
          throw new Exception("Unable to find chromdriver");
        }
        break;
      case "safari":
        // capabilities = DesiredCapabilities.internetExplorer();
        break;
    }

    return capabilities;
  }
コード例 #6
0
 @Parameters("browser")
 @Test
 public void dropdownTest(String b) throws MalformedURLException, Throwable {
   DesiredCapabilities cap = null;
   if (b.equals("firefox")) {
     cap = DesiredCapabilities.firefox();
     cap.setBrowserName("firefox");
     cap.setPlatform(Platform.ANY);
   } else if (b.equals("chrome")) {
     cap = DesiredCapabilities.chrome();
     cap.setBrowserName("chrome");
     cap.setPlatform(Platform.WINDOWS);
   }
   RemoteWebDriver driver = new RemoteWebDriver(new URL("http://localhost:4444/wb/hub"), cap);
   driver.get("http://newtours.demoaut.com"); // Dropdown prgm copy paste.
   driver.findElement(By.linkText("REGISTER")).click();
   Thread.sleep(3000);
   WebElement drop = driver.findElement(By.name("country"));
   List<WebElement> dropdown = drop.findElements(By.tagName("option"));
   int a = MyRandomNo(dropdown.size() - 1);
   dropdown.get(a).click();
   if (dropdown.get(a).isSelected()) {
     System.out.println(dropdown.get(a).getText() + "is active");
   } else {
     System.out.println(dropdown.get(a).getText() + "is not active");
   }
 }
コード例 #7
0
  @Parameters("browser")
  @Test
  public void dropdownTest(String b) throws MalformedURLException {
    System.out.println(b);
    DesiredCapabilities cap = null;
    if (b.equals("firefox")) {
      cap = DesiredCapabilities.firefox();
      cap.setBrowserName("firefox");
      cap.setPlatform(Platform.ANY);
    } else if (b.equals("chrome")) {
      cap = DesiredCapabilities.chrome();
      cap.setBrowserName("chrome");
      cap.setPlatform(Platform.WINDOWS);
    }
    RemoteWebDriver driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), cap);
    driver.get("http://newtours.demoaut.com");
    driver.findElement(By.linkText("REGISTER")).click();
    WebElement drop = driver.findElement(By.name("country"));
    List<WebElement> dropdown = drop.findElements(By.tagName("option"));
    System.out.println(dropdown.size());
    for (int i = 0; i < dropdown.size(); i++) {
      dropdown.get(i).click();

      if (dropdown.get(i).isSelected()) {
        System.out.println(dropdown.get(i).getText() + " is active");
      } else {
        System.out.println(dropdown.get(i).getText() + " is inactive");
      }
    }
  }
コード例 #8
0
  private WebDriver setRemoteServer(Map<String, String> getsessionConfig) {
    DesiredCapabilities cap = null;
    browser = System.getProperty("browser");

    if (browser == null) browser = getsessionConfig.get("browser").toString();
    if (browser.equalsIgnoreCase("firefox")) {
      cap = DesiredCapabilities.firefox();
    } else if (browser.equalsIgnoreCase("chrome")) {
      cap = DesiredCapabilities.chrome();
    } else if (browser.equalsIgnoreCase("ie")
        || browser.equalsIgnoreCase("internetexplorer")
        || browser.equalsIgnoreCase("InternetExplorer")) {
      cap = DesiredCapabilities.internetExplorer();
    }

    String seleniumhubAddress = System.getProperty("hub");
    if (seleniumhubAddress == null) {
      seleniumhubAddress = getsessionConfig.get("seleniumserverhost1");
    }
    URL serverhost = null;

    try {
      serverhost = new URL(seleniumhubAddress);
    } catch (MalformedURLException e) {
      e.printStackTrace();
    }
    cap.setJavascriptEnabled(true);
    return new RemoteWebDriver(serverhost, cap);
  }
コード例 #9
0
  public WebDriver getDriver() throws IOException, URISyntaxException {
    switch (driverType) {
      case FIREFOX:
        {
          FirefoxDriver wd = new FirefoxDriver();
          return wd;
        }
      case CHROME:
        {
          DesiredCapabilities desired = DesiredCapabilities.chrome();
          ChromeDriverService chromeService;
          ChromeDriverService.Builder builder =
              new ChromeDriverService.Builder().usingAnyFreePort();
          if (new File(chromeBinPath).exists()) {
            logger.info("using file location [{}]", chromeBinPath);
            System.setProperty("webdriver.chrome.driver", chromeBinPath);
            builder = builder.usingDriverExecutable(new File(chromeBinPath));
          } else if (chromeBinPath != null) {
            logger.info("finding classpath resource at :[{}]", chromeBinPath);
            File chromeDriver = new ClassPathResource(chromeBinPath).getFile();
            System.setProperty("webdriver.chrome.driver", chromeDriver.getAbsolutePath());
            builder = builder.usingDriverExecutable(chromeDriver);
          }

          chromeService = builder.build();
          logger.info("Starting Chrome Driver Server...");
          chromeService.start();
          ChromeDriver wd = new ChromeDriver(chromeService, desired);
          return wd;
        }
    }
    throw new RuntimeException("no driver specified");
  }
コード例 #10
0
  @BeforeClass
  public static void prepare() throws Exception {

    hub = GridTestHelper.getHub();
    registry = hub.getRegistry();
    registry.setThrowOnCapabilityNotPresent(false);

    remote = GridTestHelper.getRemoteWithoutCapabilities(hub.getUrl(), GridRole.NODE);
    remote.setMaxConcurrent(100);

    DesiredCapabilities caps = null;

    // firefox

    caps = DesiredCapabilities.firefox();
    caps.setCapability(FirefoxDriver.BINARY, locationFF7);
    caps.setVersion("7");
    remote.addBrowser(caps, 1);
    caps = DesiredCapabilities.firefox();
    caps.setCapability(FirefoxDriver.BINARY, locationFF3);
    caps.setVersion("3");
    remote.addBrowser(caps, 1);
    caps = DesiredCapabilities.firefox();
    caps.setCapability(FirefoxDriver.BINARY, "should be overwritten");
    caps.setVersion("20");
    remote.addBrowser(caps, 1);

    // chrome

    caps = DesiredCapabilities.chrome();
    caps.setCapability("chrome_binary", locationChrome27);
    caps.setVersion("27");
    remote.addBrowser(caps, 1);
    caps = DesiredCapabilities.chrome();
    caps.setCapability("chrome_binary", locationChrome29);
    caps.setVersion("29");
    remote.addBrowser(caps, 2);
    caps = DesiredCapabilities.chrome();
    caps.setCapability("chrome_binary", "should be overwritten");
    caps.setVersion("30");
    remote.addBrowser(caps, 1);

    remote.setRemoteServer(new SeleniumServer(remote.getConfiguration()));
    remote.startRemoteServer();
    remote.sendRegistrationRequest();
    RegistryTestHelper.waitForNode(registry, 1);
  }
コード例 #11
0
ファイル: TestBase.java プロジェクト: ibmer921150/xero-test
  protected void setUp() throws Exception {
    if (!isConfigured()) {
      DOMConfigurator.configure("log4j.xml");
      iConfigured = true;
    }
    configProperties = new Properties();
    try {
      configProperties.load(
          TestBase.class.getClassLoader().getResourceAsStream("config.properties"));
    } catch (IOException e) {
      e.printStackTrace();
    }

    useRemote = Boolean.parseBoolean(configProperties.getProperty("use_remote"));

    bro = configProperties.getProperty("browser");
    chromeDriver = configProperties.getProperty("chromedriver");
    ieDriver = configProperties.getProperty("iedriver");

    if (useRemote) {
      File profileDir = new File(getClass().getResource("/seleniumProfile").getFile());
      FirefoxProfile profile = new FirefoxProfile(profileDir);
      DesiredCapabilities capabilities = DesiredCapabilities.firefox();
      capabilities.setCapability(FirefoxDriver.PROFILE, profile);
      capabilities.setCapability("binary", "/usr/bin/firefox");
      String remoteUrl = configProperties.getProperty("selenium_remote_url");
      driver = new RemoteWebDriver(new URL(remoteUrl), capabilities);
      ((RemoteWebDriver) driver).setFileDetector(new LocalFileDetector());
    } else {
      if (bro.toLowerCase().equals("firefox")) {

        File profileDir = null;
        profileDir = new File(getClass().getResource("/seleniumProfile").getFile());
        FirefoxProfile profile = new FirefoxProfile(profileDir);
        driver = new FirefoxDriver(profile);
      }
      if (bro.toLowerCase().equals("chrome")) {
        System.setProperty("webdriver.chrome.driver", chromeDriver);
        Map<String, Object> prefs = new HashMap<String, Object>();
        prefs.put("download.default_directory", "target");
        DesiredCapabilities caps = DesiredCapabilities.chrome();
        ChromeOptions options = new ChromeOptions();
        options.setExperimentalOption("prefs", prefs);
        caps.setCapability(ChromeOptions.CAPABILITY, options);
        driver = new ChromeDriver(caps);
      }
      if (bro.toLowerCase().equals("ie")) {
        DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
        capabilities.setCapability(
            InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
        System.setProperty("webdriver.ie.driver", ieDriver);
        capabilities.setCapability("ignoreZoomSetting", true);
        capabilities.setCapability("nativeEvents", false);
        driver = new InternetExplorerDriver(capabilities);
      }
    }
    int timeout = Integer.parseInt(configProperties.getProperty("driver_timeout"));
    driver.manage().timeouts().implicitlyWait(timeout, TimeUnit.SECONDS);
  }
コード例 #12
0
 @Before
 public void setUp() throws Exception {
   DesiredCapabilities caps = DesiredCapabilities.chrome();
   caps.setCapability("platform", "Windows XP");
   caps.setCapability("version", "43.0");
   driver = new RemoteWebDriver(new URL(URL), caps);
   driver.get("https://www.op.fi/op?sym=" + stock + ".HSE&id=32455&srcpl=3");
 }
コード例 #13
0
  public static DesiredCapabilities of(Browser browser) {
    if (browser == null) {
      return null;
    }

    DesiredCapabilities caps;

    switch (browser) {
      case chrome:
        caps = DesiredCapabilities.chrome();
        break;

      case ff:
        caps = DesiredCapabilities.firefox();
        //        caps.setCapability(FirefoxDriver.MARIONETTE,
        //
        // Boolean.getBoolean(FirefoxDriver.SystemProperty.DRIVER_USE_MARIONETTE));
        break;

      case htmlunit:
        caps = DesiredCapabilities.htmlUnit();
        caps.setJavascriptEnabled(false);
        break;

      case htmlunit_js:
        caps = DesiredCapabilities.htmlUnit();
        caps.setJavascriptEnabled(true);
        break;

      case ie:
        caps = DesiredCapabilities.internetExplorer();
        break;

      case operablink:
        caps = DesiredCapabilities.operaBlink();
        break;

      case phantomjs:
        caps = DesiredCapabilities.phantomjs();
        break;

      case safari:
        caps = DesiredCapabilities.safari();
        break;

      default:
        throw new RuntimeException("Cannot determine browser config to use");
    }

    String version = System.getProperty("selenium.browser.version");
    if (version != null) {
      caps.setVersion(version);
    }

    caps.setCapability(HAS_NATIVE_EVENTS, Boolean.getBoolean("selenium.browser.native_events"));

    return caps;
  }
コード例 #14
0
  static {
    _desiredCapabilities = DesiredCapabilities.chrome();

    Map<String, Object> preferences = new HashMap<>();

    preferences.put("download.default_directory", TestPropsValues.OUTPUT_DIR_NAME);
    preferences.put("download.prompt_for_download", false);

    _desiredCapabilities.setCapability("chrome.prefs", preferences);
  }
コード例 #15
0
 public DesiredCapabilities getChromeCapabilities() {
   DesiredCapabilities capabilities = DesiredCapabilities.chrome();
   capabilities.setCapability(
       "chrome.switches", Collections.singletonList("--no-default-browser-check"));
   HashMap<String, String> chromePreferences = new HashMap<>();
   chromePreferences.put("profile.password_manager_enabled", "false");
   capabilities.setCapability("chrome.prefs", chromePreferences);
   System.out.println(proxy());
   return addProxySettings(capabilities, proxy());
 }
コード例 #16
0
  private static Capabilities getCapabilities(String driverType) {
    DesiredCapabilities result = new DesiredCapabilities();

    switch (driverType) {
      case BrowserType.FIREFOX:
        result = DesiredCapabilities.firefox();
        FirefoxProfile profile =
            (FirefoxProfile) ConfigLoader.config().getProperty("firefox.profile");
        if (profile == null) {
          profile = new FirefoxProfile();
          if (ConfigLoader.config().getBoolean("webdriver.accept.java", true)) {
            profile.setPreference("plugin.state.java", 2);
          }
          if (ConfigLoader.config().getBoolean("webdriver.accept.ssl", true)) {
            profile.setAcceptUntrustedCertificates(true);
            profile.setAssumeUntrustedCertificateIssuer(true);
          }
          if (ConfigLoader.config().getBoolean("webdriver.autodownload", true)) {
            profile.setPreference("browser.download.folderList", 2);
            profile.setPreference("browser.helperApps.alwaysAsk.force", false);
            profile.setPreference("browser.download.manager.showWhenStarting", false);
            profile.setPreference("browser.helperApps.neverAsk.saveToDisk", autoDownloadFiles());
          }
        }
        result.setCapability(FirefoxDriver.PROFILE, profile);
        result.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
        break;
      case BrowserType.IE:
        result = DesiredCapabilities.internetExplorer();
        result.setCapability("ignoreProtectedModeSettings", true);
        result.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
        break;
      case BrowserType.CHROME:
        result = DesiredCapabilities.chrome();
        ChromeOptions chromOptions = new ChromeOptions();
        //
        //	chromOptions.setExperimentalOption("excludeSwitches",Lists.newArrayList("ignore-certificate-errors"));
        chromOptions.addArguments("chrome.switches", "--disable-extensions");
        result.setCapability(ChromeOptions.CAPABILITY, chromOptions);
        result.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
        break;
      default:
        result = new DesiredCapabilities(driverType, "", Platform.ANY);
        break;
    }
    String proxy = ConfigLoader.config().getString("webdriver.proxy");
    if (!Strings.isNullOrEmpty(proxy)) {
      Proxy p = new Proxy();
      p.setHttpProxy(proxy).setSslProxy(proxy);
      result.setCapability(CapabilityType.PROXY, p);
      log.info("Using proxy {}", proxy);
    }
    return concatenate(result, capabilities);
  }
コード例 #17
0
    @Override
    public void setSystemProperty(Configuration configInstance, Capabilities capabilities) {
      String brofserName = capabilities.getBrowserName();

      if (DesiredCapabilities.chrome().getBrowserName().equals(brofserName))
        CHROME.setSystemProperty(configInstance);
      if (DesiredCapabilities.internetExplorer().getBrowserName().equals(brofserName))
        INTERNETEXPLORER.setSystemProperty(configInstance);
      if (DesiredCapabilities.phantomjs().getBrowserName().equals(brofserName))
        PHANTOMJS.setSystemProperty(configInstance);
    }
コード例 #18
0
  public SeleniumProvider(String gridUrl, String baseUrl) {
    DesiredCapabilities capabilities = DesiredCapabilities.chrome();
    this.baseURL = baseUrl;
    try {
      this.driver = new RemoteWebDriver(new URL(gridUrl), capabilities);
    } catch (MalformedURLException e) {
      LOGGER.error(e.getMessage());
    }

    browserDriver = new BrowserDriver(driver, this.baseURL);
    this.selenium = browserDriver.getSelenium();
  }
コード例 #19
0
  private static void initDriver(String browser) {
    String browserName = System.getProperty("browser", browser);
    String browserRemoteName = System.getProperty("remote", "local");

    if (browserRemoteName.equals("local")) {
      switch (browserName) {
        case "chrome":
        default:
          driver = new ChromeDriver();
          break;
        case "firefox":
          driver = new FirefoxDriver();
          break;
        case "ie":
          driver = new InternetExplorerDriver();
          break;
        case "html":
          driver = new HtmlUnitDriver();
          break;
        case "phantomjs":
          driver = new PhantomJSDriver();
          break;
      }
    } else {
      DesiredCapabilities caps;
      switch (browserName) {
        case "chrome":
        default:
          caps = DesiredCapabilities.chrome();
          break;
        case "firefox":
          caps = DesiredCapabilities.firefox();
          break;
        case "ie":
          caps = DesiredCapabilities.internetExplorer();
          break;
        case "html":
          caps = DesiredCapabilities.htmlUnitWithJs();
          break;
        case "phantomjs":
          caps = DesiredCapabilities.phantomjs();
          break;
      }
      try {
        driver = new RemoteWebDriver(new URL(browserRemoteName), caps);
      } catch (Exception ex) {
        System.out.println(ex.getMessage());
      }
    }

    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    driver.manage().window().maximize();
  }
コード例 #20
0
 {
   put(DesiredCapabilities.chrome(), "org.openqa.selenium.chrome.ChromeDriver");
   put(DesiredCapabilities.firefox(), "org.openqa.selenium.firefox.FirefoxDriver");
   put(DesiredCapabilities.htmlUnit(), "org.openqa.selenium.htmlunit.HtmlUnitDriver");
   put(
       DesiredCapabilities.internetExplorer(),
       "org.openqa.selenium.ie.InternetExplorerDriver");
   put(DesiredCapabilities.opera(), "com.opera.core.systems.OperaDriver");
   put(DesiredCapabilities.safari(), "org.openqa.selenium.safari.SafariDriver");
   put(DesiredCapabilities.iphone(), "org.openqa.selenium.iphone.IPhoneDriver");
   put(DesiredCapabilities.ipad(), "org.openqa.selenium.iphone.IPhoneDriver");
   put(DesiredCapabilities.phantomjs(), "org.openqa.selenium.phantomjs.PhantomJSDriver");
 }
コード例 #21
0
ファイル: WebDriverEnum.java プロジェクト: usark21/BDD
 @Override
 public WebDriver getWebDriver() {
   if (null != remote_url) {
     try {
       DesiredCapabilities capability = DesiredCapabilities.chrome();
       return new WebAppDriver(
           new RemoteWebDriver(
               new URL("http://localhost:4444/wd/hub"), (Capabilities) capability));
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
   return new ChromeDriver();
 }
コード例 #22
0
ファイル: WebDriverFactory.java プロジェクト: cuiken/UMS
  public static WebDriver createDriver(String driverName) {
    WebDriver driver = null;

    if (BrowserType.firefox.name().equals(driverName)) {
      driver = new FirefoxDriver();
    } else if (BrowserType.ie.name().equals(driverName)) {
      driver = new InternetExplorerDriver();
    } else if (BrowserType.chrome.name().equals(driverName)) {
      driver = new ChromeDriver();
    } else if (BrowserType.htmlunit.name().equals(driverName)) {
      driver = new HtmlUnitDriver(true);
    } else if (driverName.startsWith(BrowserType.remote.name())) {
      String[] params = driverName.split(":");
      Assert.isTrue(
          params.length == 4,
          "Remote driver is not right, accept format is \"remote:localhost:4444:firefox\", but the input is\""
              + driverName
              + "\"");

      String remoteHost = params[1];
      String remotePort = params[2];
      String driverType = params[3];

      String remoteUrl = "http://" + remoteHost + ":" + remotePort + "/wd/hub";

      DesiredCapabilities cap = null;
      if (BrowserType.firefox.name().equals(driverType)) {
        cap = DesiredCapabilities.firefox();
      } else if (BrowserType.ie.name().equals(driverType)) {
        cap = DesiredCapabilities.internetExplorer();
      } else if (BrowserType.chrome.name().equals(driverType)) {
        cap = DesiredCapabilities.chrome();
      }

      try {
        driver = new RemoteWebDriver(new URL(remoteUrl), cap);
      } catch (MalformedURLException e) {
        throw new RuntimeException(e);
      }
    }

    Assert.notNull(driver, "Driver could be found by name:" + driverName);

    return driver;
  }
コード例 #23
0
ファイル: SeleniumBase.java プロジェクト: takinosaji/jUnium
  @Before
  public void SetUp() {
    System.out.print("Using " + Browser + SystemHelper.LineSeparator);

    switch (Browser) {
      case Chrome:
        {
          System.setProperty("webdriver.chrome.driver", Settings.ChromeDriverPath);
          ChromeCapabilities =
              ChromeCapabilities == null ? DesiredCapabilities.chrome() : ChromeCapabilities;
          ChromeService =
              ChromeService == null ? ChromeDriverService.createDefaultService() : ChromeService;
          Driver = new ChromeDriver(ChromeService, ChromeCapabilities);
        }
        break;
      case Firefox:
        {
          InitializeFirefoxDriver();
        }
        break;
      case IE:
        {
          System.setProperty("webdriver.ie.driver", Settings.IEDriverPath);
          IECapabilities =
              IECapabilities == null ? DesiredCapabilities.internetExplorer() : IECapabilities;
          IEService =
              IEService == null ? InternetExplorerDriverService.createDefaultService() : IEService;
          Driver = new InternetExplorerDriver(IEService, IECapabilities);
        }
        break;
      default:
        {
          InitializeFirefoxDriver();
        }
        break;
    }

    Driver.manage().window().maximize();
    SmallWait = new WebDriverWait(Driver, 3);
    Wait = new WebDriverWait(Driver, 10);
    LongWait = new WebDriverWait(Driver, 30);
  }
コード例 #24
0
ファイル: SIGN_IN.java プロジェクト: lrzonca/Automation
 /** Sign in successfully (keep me signed in off)* */
 @Test
 @Parameters({"xBrowser", "xUrl"})
 public void SignIn5(String xBrowser, String xUrl) throws InterruptedException {
   System.out.println("Open URL");
   driver.get(xUrl);
   sleep(2);
   clickElement(signIn.SIGN_IN_LINK);
   insertData(signIn.USERNAME, "cookietest");
   insertData(signIn.PASSWORD, "123456");
   sleep(2);
   System.out.println("Find Element REMEMBER_CHECKBOX");
   WebElement remember = findElement(signIn.REMEMBER_CHECKBOX);
   System.out.println("Click Element REMEMBER_CHECKBOX if is selected");
   if (remember.isSelected()) {
     remember.click();
   }
   System.out.println("Find Element SIGN_IN_BUTTON");
   clickElement(signIn.SIGN_IN_BUTTON);
   sleep(5);
   System.out.println("Assertion");
   assertEquals("cookietest", findElement(signIn.LOGGED_USERNAME).getText());
   System.out.println("Close browser");
   driver.quit();
   System.out.println("Open browser");
   if (xBrowser.contains("firefox")) {
     driver = new FirefoxDriver();
   } else if (xBrowser.contains("chrome")) {
     driver = new RemoteWebDriver(service.getUrl(), DesiredCapabilities.chrome());
   } else if (xBrowser.contains("ie")) {
     DesiredCapabilities ieCapabilities = DesiredCapabilities.internetExplorer();
     ieCapabilities.setCapability(
         InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
     ieCapabilities.setCapability(CapabilityType.ForSeleniumServer.ENSURING_CLEAN_SESSION, true);
     driver = new InternetExplorerDriver(ieCapabilities);
   }
   System.out.println("Open URL");
   driver.get(xUrl);
   System.out.println("Sleep 10 sek");
   Thread.sleep(10000);
   System.out.println("Assertion");
   assertFalse(findElement(signIn.LOGGED_USERNAME).isDisplayed());
 }
コード例 #25
0
 @Test
 public void Login_01() throws InterruptedException {
   File chromedriver = new File("/Users/ZhengfeiRui/Desktop/QADownloads/chromedriver");
   System.setProperty("webdriver.chrome.driver", chromedriver.getAbsolutePath());
   DesiredCapabilities Capabilities = new DesiredCapabilities();
   Capabilities = DesiredCapabilities.chrome();
   Capabilities.setCapability("chrome.switches", Arrays.asList("--start-maximized"));
   driver = new ChromeDriver(Capabilities);
   System.out.println("Chrome Browser is opened");
   // driver=new SafariDriver();
   driver.get("http://107.170.213.234/catalog/");
   driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
   PageFactory.initElements(this.driver, this);
   //	testPageFactory LoginPage =PageFactory.initElements(driver, testPageFactory.class);
   LOGYOURSELFIN.click();
   EMAILADDRESS.sendKeys("*****@*****.**");
   PASSWORD.sendKeys("test123");
   SIGNIN.click();
   Thread.sleep(300);
   LOGOFF.click();
 }
コード例 #26
0
  /**
   * private method to load the Chrome Driver
   *
   * @param loadRemote
   */
  private static RemoteWebDriver loadChromeDriver(boolean loadRemote) throws Exception {

    log.info("Entering BrowserFactory class loadChromeDriver...");

    RemoteWebDriver remoteDriver = null;
    DesiredCapabilities capabilities = DesiredCapabilities.chrome();

    if (loadRemote) {

      log.info("loading Chrome driver in remote");
      log.info("Loading  Remote Run URL " + CommonUtils.readFromConfig("RemoteWebAppUrl"));
      URL url = new URL(CommonUtils.readFromConfig("RemoteWebAppUrl"));
      remoteDriver = new RemoteWebDriver(url, capabilities);
      log.info("loading IE driver in remote successful");

    } else {
      log.info("loading Generic Chrome driver");

      String hostOS = CommonUtils.getHostOperatingSystem();
      System.out.println("Host OS : " + hostOS);

      if (hostOS.equalsIgnoreCase("Mac OS X")) {
        System.setProperty(
            "webdriver.chrome.driver", "src/main/resources/browser_exe/chrome/chromedriver");
      } else {
        System.setProperty(
            "webdriver.chrome.driver", "src/main/resources/browser_exe/chrome/chromedriver.exe");
      }
      remoteDriver = new ChromeDriver();
      log.info("loading Generic Chrome driver successful");
    }

    log.info("Exiting BrowserFactory class loadChromeDriver...");

    return remoteDriver;
  }
コード例 #27
0
 @BeforeMethod
 @Parameters("url")
 public void beforeTest(String url) throws InterruptedException {
   System.setProperty("webdriver.chrome.driver", project_path + "/libs/chromedriver.exe");
   DesiredCapabilities capabilities = DesiredCapabilities.chrome();
   ChromeOptions options = new ChromeOptions();
   options.addArguments("test-type");
   capabilities.setCapability("chrome.binary", project_path + "/libs/chromedriver.exe");
   capabilities.setCapability(ChromeOptions.CAPABILITY, options);
   driver = new ChromeDriver(capabilities);
   driver.manage().window().maximize();
   driver.get(url);
   Thread.sleep(10000);
   if (driver.findElement(By.xpath("//*[@id='SubscriptionModal']")).isDisplayed()) {
     driver.findElement(By.id("emailIdInModal")).clear();
     driver.findElement(By.id("emailIdInModal")).sendKeys("*****@*****.**");
     Thread.sleep(1000);
     driver.findElement(By.xpath("//*[@class='button postfix redbutton']")).click();
     new WebDriverWait(driver, 30)
         .until(
             ExpectedConditions.elementToBeClickable(By.xpath("//*[@id='SubscribeModal']/a/img")));
     driver.findElement(By.xpath("//*[@id='SubscribeModal']/a/img")).click();
   }
 }
コード例 #28
0
 /** Initializes web driver instance */
 @BeforeClass(alwaysRun = true)
 public void initializeWebDriver() {
   webDriver = new HtmlUnitDriver(DesiredCapabilities.chrome());
 }
コード例 #29
0
/**
 * There is information about supported {@link WebDriver} implementors <br>
 * - {@link FirefoxDriver}<br>
 * - {@link ChromeDriver}<br>
 * - {@link InternetExplorerDriver}<br>
 * - {@link SafariDriver}<br>
 * - {@link PhantomJSDriver}<br>
 * - {@link RemoteWebDriver}<br>
 * - {@link AndroidDriver}<br>
 * - {@link IOSDriver}<br>
 * <br>
 * - is browser only<br>
 * - is for mobile applications only<br>
 * Additional info:<br>
 * - default {@link Capabilities}<br>
 * - information about {@link DriverService}<br>
 * - can {@link WebDriver} be started remotely?<br>
 * - is {@link WebDriver} require URL of remotely or locally started<br>
 * server. ({@link SeleniumServer} or Appium Node.js server (see
 * http://appium.io/slate/en/master/?ruby#appium-design)<br>
 */
public enum ESupportedDrivers {
  /**
   * <b>Required {@link WebDriver} implementor</b>: {@link FirefoxDriver} <br>
   * <br>
   * <b>Default {@link Capabilities}</b>: {@link DesiredCapabilities#firefox()}<br>
   * <br>
   * <b>{@link DriverService}</b>: none<br>
   * <br>
   * <b>Starts</b>: locally<br>
   * browser only
   */
  FIREFOX(
      DesiredCapabilities.firefox(), FirefoxDriver.class, true, false, null, null, false, false),
  /**
   * <b>Required {@link WebDriver} implementor</b>: {@link ChromeDriver} <br>
   * <br>
   * <b>Default {@link Capabilities}</b>: {@link DesiredCapabilities#chrome()}<br>
   * <br>
   * <b>{@link DriverService}</b>: {@link ChromeDriverService}<br>
   * <br>
   * <b>Starts</b>: locally<br>
   * browser only
   */
  CHROME(
      DesiredCapabilities.chrome(),
      ChromeDriver.class,
      true,
      false,
      EServices.CHROMESERVICE,
      null,
      false,
      false),
  /**
   * <b>Required {@link WebDriver} implementor</b>: {@link InternetExplorerDriver} <br>
   * <br>
   * <b>Default {@link Capabilities}</b>: {@link DesiredCapabilities#internetExplorer()}<br>
   * <br>
   * <b>{@link DriverService}</b>: {@link InternetExplorerDriverService}<br>
   * <br>
   * <b>Starts</b>: locally<br>
   * browser only<br>
   * <br>
   * <b>Additionally:</b> Windows only<br>
   */
  INTERNETEXPLORER(
      DesiredCapabilities.internetExplorer(),
      InternetExplorerDriver.class,
      true,
      false,
      EServices.IEXPLORERSERVICE,
      null,
      false,
      false),
  /**
   * <b>Required {@link WebDriver} implementor</b>: {@link SafariDriver} <br>
   * <br>
   * <b>Default {@link Capabilities}</b>: {@link DesiredCapabilities#safari()}<br>
   * <br>
   * <b>{@link DriverService}</b>: none<br>
   * <br>
   * <b>Starts</b>: locally<br>
   * browser only
   */
  SAFARI(DesiredCapabilities.safari(), SafariDriver.class, true, false, null, null, false, false),
  /**
   * <b>Required {@link WebDriver} implementor</b>: {@link PhantomJSDriver} <br>
   * <br>
   * <b>Default {@link Capabilities}</b>: {@link DesiredCapabilities#phantomjs()}<br>
   * <br>
   * <b>{@link DriverService}</b>: {@link PhantomJSDriverService}<br>
   * <br>
   * <b>Starts</b>: locally<br>
   * browser only
   */
  PHANTOMJS(
      DesiredCapabilities.phantomjs(),
      PhantomJSDriver.class,
      true,
      false,
      EServices.PHANTOMJSSERVICE,
      null,
      false,
      false),
  /**
   * <b>Required {@link WebDriver} implementor</b>: {@link AndroidDriver}<br>
   * <br>
   * <b>Default {@link Capabilities}</b>: {@link ExtendedDesiredCapabilities#androidChrome()}<br>
   * <br>
   * <b>{@link DriverService}</b>: none<br>
   * <br>
   * <b>Starts</b>: remotely. It requires {@link URL} of the host where Appium node server is
   * started, e.g. http://127.0.0.1:4723/wd/hub (local host). Please find information here:<br>
   * http://appium.io/getting-started.html<br>
   * browser only
   */
  ANDROID_CHROME(
      ExtendedDesiredCapabilities.androidChrome(),
      AndroidDriver.class,
      true,
      false,
      null,
      null,
      true,
      true),
  /**
   * <b>Required {@link WebDriver} implementor</b>: {@link AndroidDriver}<br>
   * <br>
   * <b>Default {@link Capabilities}</b>: {@link ExtendedDesiredCapabilities#androidBrowser()}<br>
   * <br>
   * <b>{@link DriverService}</b>: none<br>
   * <br>
   * <b>Starts</b>: remotely. It requires {@link URL} of the host where Appium node server is
   * started, e.g. http://127.0.0.1:4723/wd/hub (local host). Please find information here:<br>
   * http://appium.io/getting-started.html<br>
   * browser only
   */
  ANDROID_BROWSER(
      ExtendedDesiredCapabilities.androidBrowser(),
      AndroidDriver.class,
      true,
      false,
      null,
      null,
      true,
      true),
  /**
   * <b>Required {@link WebDriver} implementor</b>: {@link AndroidDriver}<br>
   * <br>
   * <b>Default {@link Capabilities}</b>: {@link ExtendedDesiredCapabilities#androidChromium()}<br>
   * <br>
   * <b>{@link DriverService}</b>: none<br>
   * <br>
   * <b>Starts</b>: remotely. It requires {@link URL} of the host where Appium node server is
   * started, e.g. http://127.0.0.1:4723/wd/hub (local host). Please find information here:<br>
   * http://appium.io/getting-started.html<br>
   * browser only
   */
  ANDROID_CHROMIUM(
      ExtendedDesiredCapabilities.androidChromium(),
      AndroidDriver.class,
      true,
      false,
      null,
      null,
      true,
      true),
  /**
   * <b>Required {@link WebDriver} implementor</b>: {@link IOSDriver}<br>
   * <br>
   * <b>Default {@link Capabilities}</b>: {@link ExtendedDesiredCapabilities#iosSafari()}<br>
   * <br>
   * <b>{@link DriverService}</b>: none<br>
   * <br>
   * <b>Starts</b>: remotely. It requires {@link URL} of the host where Appium node server is
   * started, e.g. http://127.0.0.1:4723/wd/hub (local host). Please find information here:<br>
   * http://appium.io/getting-started.html<br>
   * browser only
   */
  IOS_SAFARI(
      ExtendedDesiredCapabilities.iosSafari(),
      IOSDriver.class,
      true,
      false,
      null,
      null,
      true,
      true),

  /**
   * <b>Required {@link WebDriver} implementor</b>: {@link RemoteWebDriver} <br>
   * <br>
   * <b>Default {@link Capabilities}</b>: {@link DesiredCapabilities#firefox()()}<br>
   * <br>
   * <b>Starts</b>: locally and remotely. When it is started locally {@link SeleniumServer} is
   * started it the same time.<br>
   * browser only<br>
   * If it needs to be launched remotely it requires {@link URL} of the host where Appium node
   * server (if {@link ExtendedDesiredCapabilities#androidChrome()} or {@link
   * ExtendedDesiredCapabilities#iosSafari()} are used) or {@link SeleniumServer} are started, e.g.
   * http://127.0.0.1:4723/wd/hub (local host). Information about Appium node server please find
   * here:<br>
   * http://appium.io/getting-started.html<br>
   * Information about {@link SeleniumServer}: https://code.google.com/p/selenium/wiki/Grid2<br>
   * <br>
   * <b>{@link DriverService}</b>: optionally. If it is run locally with {@link
   * DesiredCapabilities#chrome()}, {@link DesiredCapabilities#internetExplorer()} or {@link
   * DesiredCapabilities#phantomjs()} then {@link ChromeDriverService}, {@link
   * InternetExplorerDriverService} or {@link PhantomJSDriverService} should be set up respectively
   * <br>
   */
  REMOTE(
      DesiredCapabilities.firefox(),
      RemoteWebDriver.class,
      true,
      false,
      null,
      new RemoteSeleniumServerLauncher(),
      true,
      false) {
    @Override
    public void setSystemProperty(Configuration configInstance, Capabilities capabilities) {
      String brofserName = capabilities.getBrowserName();

      if (DesiredCapabilities.chrome().getBrowserName().equals(brofserName))
        CHROME.setSystemProperty(configInstance);
      if (DesiredCapabilities.internetExplorer().getBrowserName().equals(brofserName))
        INTERNETEXPLORER.setSystemProperty(configInstance);
      if (DesiredCapabilities.phantomjs().getBrowserName().equals(brofserName))
        PHANTOMJS.setSystemProperty(configInstance);
    }
  },
  /**
   * <b>Required {@link WebDriver} implementor</b>: {@link AndroidDriver} <br>
   * <br>
   * <b>Default {@link Capabilities}</b>: empty. They should be defined explicitly. Here is an
   * example: <br>
   * &nbsp;&nbsp;"deviceName":{<br>
   * &nbsp;&nbsp;&nbsp;&nbsp;"value":"desired device name e.g. Android Emulator, NEXUS and so on"
   * <br>
   * &nbsp;&nbsp;},<br>
   * &nbsp;&nbsp;"app":{<br>
   * &nbsp;&nbsp;&nbsp;&nbsp;"value":"absolute path to desired *.apk file"<br>
   * &nbsp;&nbsp;}<br>
   * <br>
   * It is enough for the successful starting. Also see {@link MobileCapabilityType}<br>
   * <br>
   * <b>Starts</b>: remotely. It requires {@link URL} of the host where Appium node server is
   * started, e.g. http://127.0.0.1:4723/wd/hub (local host). Please find information here:<br>
   * http://appium.io/getting-started.html<br>
   * mobile apps only
   */
  ANDROID_APP(new DesiredCapabilities(), AndroidDriver.class, false, true, null, null, true, true),

  /**
   * <b>Required {@link WebDriver} implementor</b>: {@link AndroidDriver} <br>
   * <br>
   * <b>Default {@link Capabilities}</b>: empty. They should be defined explicitly. Here is an
   * example: <br>
   * &nbsp;&nbsp;"deviceName":{<br>
   * &nbsp;&nbsp;&nbsp;&nbsp;"value":"desired device name e.g. Android Emulator, NEXUS and so on"
   * <br>
   * &nbsp;&nbsp;},<br>
   * &nbsp;&nbsp;"app":{<br>
   * &nbsp;&nbsp;&nbsp;&nbsp;"value":"absolute path to desired *.apk file"<br>
   * &nbsp;&nbsp;}<br>
   * <br>
   * It is enough for the successful starting. Also see {@link MobileCapabilityType}<br>
   * <br>
   * <b>Starts</b>: remotely. It requires {@link URL} of the host where Appium node server is
   * started, e.g. http://127.0.0.1:4723/wd/hub (local host). Please find information here:<br>
   * http://appium.io/getting-started.html<br>
   * mobile apps only
   */
  SELENDROID_APP(
      ExtendedDesiredCapabilities.selendroid(),
      AndroidDriver.class,
      false,
      true,
      null,
      null,
      true,
      true),

  /**
   * <b>Required {@link WebDriver} implementor</b>: {@link IOSDriver} <br>
   * <br>
   * <b>Default {@link Capabilities}</b>: empty. They should be defined explicitly. Here is an
   * example: <br>
   * &nbsp;&nbsp;"platformVersion":{<br>
   * &nbsp;&nbsp;&nbsp;&nbsp;"value":"7.1"<br>
   * &nbsp;&nbsp;},<br>
   * &nbsp;&nbsp;"deviceName":{<br>
   * &nbsp;&nbsp;&nbsp;&nbsp;"value":"desired device name e.g. iPhone Simulator"<br>
   * &nbsp;&nbsp;},<br>
   * &nbsp;&nbsp;"app":{<br>
   * &nbsp;&nbsp;&nbsp;&nbsp;"value":"absolute path to desired *.app"<br>
   * &nbsp;&nbsp;}<br>
   * <br>
   * It is enough for the successful starting. Also see {@link MobileCapabilityType}<br>
   * <br>
   * <b>Starts</b>: remotely. It requires {@link URL} of the host where Appium node server is
   * started, e.g. http://127.0.0.1:4723/wd/hub (local host). Please find information here:<br>
   * http://appium.io/getting-started.html<br>
   * mobile apps only
   */
  IOS_APP(new DesiredCapabilities(), IOSDriver.class, false, true, null, null, true, true);

  public static ESupportedDrivers parse(String original) {
    String parcingStr = original.toUpperCase().trim();

    ESupportedDrivers[] values = ESupportedDrivers.values();
    for (ESupportedDrivers enumElem : values)
      if (parcingStr.equals(enumElem.toString())) return enumElem;
    throw new IllegalArgumentException(
        "Webdriver with specified name " + original + " is not supported");
  }

  private DesiredCapabilities capabilities;
  private Class<? extends WebDriver> driverClazz;
  private EServices service;
  final ILocalServerLauncher serverLauncher;
  private final boolean startsRemotely;

  private final boolean requiresRemoteURL;
  private final boolean isForBrowser;
  private final boolean isForMobileApp;

  private ESupportedDrivers(
      DesiredCapabilities capabilities,
      Class<? extends WebDriver> driverClazz,
      boolean isForBrowser,
      boolean isForMobileApp,
      EServices sevice,
      ILocalServerLauncher serverLauncher,
      boolean startsRemotely,
      boolean requiresRemoteURL) {
    this.capabilities = capabilities;
    this.driverClazz = driverClazz;
    this.service = sevice;
    this.serverLauncher = serverLauncher;
    this.startsRemotely = startsRemotely;
    this.requiresRemoteURL = requiresRemoteURL;
    this.isForBrowser = isForBrowser;
    this.isForMobileApp = isForMobileApp;
  }

  /** @return {@link Capabilities} Default capabilities of given {@link WebDriver} implementor */
  public DesiredCapabilities getDefaultCapabilities() {
    return capabilities;
  }

  /** @return Class of supported {@link WebDriver} implementor */
  public Class<? extends WebDriver> getUsingWebDriverClass() {
    return driverClazz;
  }

  /**
   * Starts remote server locally It is possible to launch {@link SeleniumServer} locally for now
   */
  public synchronized void launchRemoteServerLocallyIfWasDefined() {
    if (serverLauncher == null) return;
    if (serverLauncher.isLaunched()) return;
    try {
      serverLauncher.launch();
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  /** @return flag of necessity of URL (remote server) */
  public boolean requiresRemoteURL() {
    return requiresRemoteURL;
  }

  /**
   * @param configInstance . An instance of {@link Configuration} where path to chromedriver*,
   *     IEDriverServer.exe or phantomjs* are defined
   */
  private void setSystemProperty(Configuration configInstance) {
    if (service != null) this.service.setSystemProperty(configInstance);
  }

  /**
   * It is useful for {@link RemoteWebDriver} instantiation. Local services depend on capabilities
   */
  public void setSystemProperty(Configuration configInstance, Capabilities ignored) {
    setSystemProperty(configInstance);
  }

  /** @return flag of of possibility to start {@link WebDriver} implementor remotely */
  public boolean startsRemotely() {
    return startsRemotely;
  }

  public boolean isForBrowser() {
    return isForBrowser;
  }

  public boolean isForMobileApp() {
    return isForMobileApp;
  }
}
 public RemoteWebDriver getChromeDriver() {
   return getRemoteDriver(DesiredCapabilities.chrome());
 }