Example usage for org.openqa.selenium WebDriver get

List of usage examples for org.openqa.selenium WebDriver get

Introduction

In this page you can find the example usage for org.openqa.selenium WebDriver get.

Prototype

void get(String url);

Source Link

Document

Load a new web page in the current browser window.

Usage

From source file:ObjectTestFactory.StartTest.java

public Boolean GoToSite(WebDriver driver, String URL) throws Exception {
    Boolean result = true;/*from  ww  w . j av  a2  s . co  m*/
    try {
        driver.get(URL);
    } catch (Exception ex) {
        result = false;
    }
    return result;
}

From source file:ohtu.Tester2.java

public static void main(String[] args) {
    WebDriver driver = new HtmlUnitDriver();
    driver.get("http://localhost:8090");
    WebElement element = driver.findElement(By.linkText("register new user"));
    element.click();/*from  w w w. j  av  a 2s  .  c  o m*/

    element = driver.findElement(By.name("username"));
    element.sendKeys("asdfasdf");
    element = driver.findElement(By.name("password"));
    element.sendKeys("asdf1234");
    element = driver.findElement(By.name("passwordConfirmation"));
    element.sendKeys("asdf1234");
    element = driver.findElement(By.name("add"));
    element.submit();

    System.out.println(driver.getPageSource().contains("Welcome to Ohtu App!"));
}

From source file:org.apache.activemq.transport.ws.WSTransportTest.java

License:Apache License

public void doTestWebSockets(WebDriver driver) throws Exception {

    driver.get(getTestURI());

    final WebElement webStatus = driver.findElement(By.id("status"));
    final WebElement webReceived = driver.findElement(By.id("received"));

    while ("Loading" == webStatus.getText()) {
        Thread.sleep(100);//from  w w  w  .  j a  va 2 s .co m
    }

    // Skip test if browser does not support websockets..
    if (webStatus.getText() != "No WebSockets") {

        assertTrue("Should have connected", Wait.waitFor(new Wait.Condition() {

            @Override
            public boolean isSatisified() throws Exception {
                return webStatus.getText().equals("Connected");
            }
        }));

        stompConnection.connect("system", "manager");

        stompConnection.send("/queue/websocket", "Hello");
        assertTrue("Should have received message by now.", Wait.waitFor(new Wait.Condition() {
            @Override
            public boolean isSatisified() throws Exception {
                return webReceived.getText().equals("Hello");
            }
        }));

        for (int i = 1; i <= MESSAGE_COUNT; ++i) {
            stompConnection.send("/queue/websocket", "messages #" + i);
        }

        assertTrue("Should have received messages by now.", Wait.waitFor(new Wait.Condition() {
            @Override
            public boolean isSatisified() throws Exception {
                return webReceived.getText().equals("messages #" + MESSAGE_COUNT);
            }
        }));

        Thread.sleep(1000);

        assertTrue("Should have disconnected", Wait.waitFor(new Wait.Condition() {

            @Override
            public boolean isSatisified() throws Exception {
                return webStatus.getText().equals("Disconnected");
            }
        }));
    }
}

From source file:org.apache.falcon.regression.ui.search.LoginPage.java

License:Apache License

public static LoginPage open(WebDriver driver) {
    driver.get(UI_URL);
    LOGGER.info("Opened a URL: " + UI_URL);
    return PageFactory.initElements(driver, LoginPage.class);
}

From source file:org.apache.flex.html.textButton.TextButton.java

License:Apache License

public static void main(String[] args) {
    WebDriver driver = new FirefoxDriver();

    Map<String, String> argsMap = new HashMap<String, String>();
    for (String arg : args) {
        String[] keyValuePair = arg.split("=");
        argsMap.put(keyValuePair[0], keyValuePair[1]);
    }/*  w w  w .  j a  v  a  2s .c o  m*/

    final String url = argsMap.get("url");

    driver.get(url);

    WebElement element = driver.findElement(By.tagName("button"));

    try {
        // there is a button in the DOM
        if (element != null) {
            // the button x position is 100
            if (element.getCssValue("left").equals("100px"))
                System.out.println(SUCCESS);
            else
                System.out.println(FAILED);
        } else {
            System.out.println(FAILED);
        }
    } catch (Exception e) {
        System.out.println(e.getMessage());
    } finally {
        driver.quit();
    }
}

From source file:org.apache.nutch.protocol.htmlunit.HtmlUnitWebDriver.java

License:Apache License

public static WebDriver getDriverForPage(String url, Configuration conf) {
    long pageLoadTimout = conf.getLong("page.load.delay", 3);
    enableJavascript = conf.getBoolean("htmlunit.enable.javascript", true);
    enableCss = conf.getBoolean("htmlunit.enable.css", false);
    javascriptTimeout = conf.getLong("htmlunit.javascript.timeout", 3500);
    int redirects = Integer.parseInt(conf.get("http.redirect.max", "0"));
    enableRedirect = redirects <= 0 ? false : true;
    maxRedirects = redirects;/*w  w  w  .  j  a  v  a  2 s .  co  m*/

    WebDriver driver = null;

    try {
        driver = new HtmlUnitWebDriver();
        driver.manage().timeouts().pageLoadTimeout(pageLoadTimout, TimeUnit.SECONDS);
        driver.get(url);
    } catch (Exception e) {
        if (e instanceof TimeoutException) {
            LOG.debug("HtmlUnit WebDriver: Timeout Exception: Capturing whatever loaded so far...");
            return driver;
        }
        cleanUpDriver(driver);
        throw new RuntimeException(e);
    }

    return driver;
}

From source file:org.apache.nutch.protocol.interactiveselenium.ListImageHandler.java

License:Apache License

public void processDriver(WebDriver driver) {
    System.out.println("=========== Into Handler_vci_classifieds ==========");
    //Get the current page URL and store the value in variable 'url'
    String url = driver.getCurrentUrl();

    //Print the value of variable in the console
    System.out.println("[ListImageHandler][processDriver] The current URL is: " + url);

    //Load a new page in the current browser windows
    driver.get(url);

    // form-input structure for search bar
    // WebElement form = driver.findElement(By.tagName("form"));
    // List<WebElement> inputs = null;
    // if (form != null) {
    //     inputs = form.findElements(By.tagName("input"));
    //     for (WebElement elem : inputs) {
    //         if (elem.isDisplayed()) {
    //             elem.clear();
    //             elem.sendKeys("gun\n");
    //             System.out.println("[ListImageHandler][processDriver] Submit keyword \"gun\"");
    //             //form.submit();
    //             break;
    //         }/*from   w ww .j a  va2 s  .c  om*/
    //     }
    // }

    // direct input html tag for search bar
    ArrayList<String> possibleName = new ArrayList<String>();
    possibleName.add("q");
    possibleName.add("searchtext");
    possibleName.add("txtSearch");

    WebElement element;
    if (inputs == null) {
        for (int i = 0; i < possibleName.size(); i++) {
            element = driver.findElement(By.name(possibleName.get(i)));
            if (element != null) {
                // send with "\n" == submit
                element.sendKeys("gun\n");
                //element.sendKeys("gun");
                //form.submit();
                System.out.println("[ListImageHandler][processDriver] Submit keyword \"gun\"");
                break;
            }
        }

    }

    // wait for finsih loading webpage, hard code timer
    try {
        System.out.println("[ListImageHandler][processDriver] before sleep");
        Thread.sleep(2000);
        System.out.println("[ListImageHandler][processDriver] after sleep");

    } catch (Exception e) {
        System.out.println("[ListImageHandler][processDriver] Exception caught");
    }

    // find all image element
    List<WebElement> findElements = driver.findElements(By.xpath("//img"));
    if (url.equals("http://www.vci-classifieds.com/")) {
        WebElement myDynamicElement = (new WebDriverWait(driver, 10))
                .until(ExpectedConditions.presenceOfElementLocated(By.id("searchlist")));
        findElements = driver.findElements(By.xpath(".//*[@id='searchlist']/center/table/tbody/tr/td/img"));
    }
    System.out.println("[ListImageHandler][processDriver] total Results Found: " + findElements.size());

    // show all the links of image
    for (WebElement elem : findElements) {
        System.out.println(elem.getAttribute("src"));
        // System.out.println(elem.toString());
    }
    System.out.println("[ListImageHandler][processDriver] " + findElements.size() + " results shown");

    // log outlinks to /tmp/outlinks
    List<WebElement> findOutlinks = driver.findElements(By.xpath("//a"));
    try (PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("/tmp/outlinks", true)))) {
        // this are all the links you like to visit
        int count = 0;
        for (WebElement elem : findOutlinks) {
            out.println(elem.getAttribute("href"));
            count++;
        }
        System.out.println("[ListImageHandler][processDriver] total Outlinks Logged: " + count);
    } catch (IOException e) {
        System.err.println(e);
    }

    // driver.close();
    // System.out.println("[ListImageHandler][processDriver] Close Driver");
}

From source file:org.apache.nutch.protocol.s2jh.HttpResponse.java

License:Apache License

/**
 * Most page can be fetched and parsed efficiently by Htmlunit, 
 * But some sites (such as ) using some special javascript tech that can't be processed by Htmlunit correctly,
 * We use Selenium WebDriver even lower process speed.
 * @param url//from   w w w . j a  v  a2 s .  co m
 * @throws Exception
 */
private void readPlainContentByWebDriver(URL url) throws Exception {

    String urlStr = url.toString();
    Http.LOG.debug("WebDriver fetching: " + url);
    String html = null;
    boolean ok = true;

    WebDriver driver = null;
    try {
        driver = new FirefoxDriver();
        driver.get(url.toString());

        int i = 0;
        while (i++ < MAX_AJAX_WAIT_SECONDS) {
            html = driver.getPageSource().trim();
            ok = isParseDataFetchLoaded(urlStr, html);
            if (ok) {
                break;
            }
            //Trigger scroll event to get ajax content                
            ((JavascriptExecutor) driver).executeScript("scroll(0," + (i * 500) + ");");
            Http.LOG.info("Sleep " + i + " seconds to wait WebDriver execution...");
            Thread.sleep(1000);
        }
    } finally {
        //Ensure driver quit
        if (driver != null) {
            driver.quit();
        }
    }

    if (ok) {
        Http.LOG.debug("Success parse page by WebDriver  for: {}", url);
        this.code = 200;
        content = html.getBytes();
    } else {
        Http.LOG.warn("Failure WebDriver parse page for: {}", url);
        Http.LOG.warn(
                "WebDriver Fetch Failure URL: " + url + ", CharsetName: " + charset + " , Page HTML=\n" + html);
    }
}

From source file:org.apache.nutch.protocol.selenium.HttpWebClient.java

License:Apache License

public static WebDriver getDriverForPage(String url, Configuration conf) {
    WebDriver driver = null;
    long pageLoadWait = conf.getLong("page.load.delay", 3);

    try {//from  w w  w . j  a v  a2 s  . co m
        String driverType = conf.get("selenium.driver", "firefox");
        boolean enableHeadlessMode = conf.getBoolean("selenium.enable.headless", false);

        switch (driverType) {
        case "firefox":
            String geckoDriverPath = conf.get("selenium.grid.binary", "/root/geckodriver");
            driver = createFirefoxWebDriver(geckoDriverPath, enableHeadlessMode);
            break;
        case "chrome":
            String chromeDriverPath = conf.get("selenium.grid.binary", "/root/chromedriver");
            driver = createChromeWebDriver(chromeDriverPath, enableHeadlessMode);
            break;
        // case "opera":
        // // This class is provided as a convenience for easily testing the
        // Chrome browser.
        // String operaDriverPath = conf.get("selenium.grid.binary",
        // "/root/operadriver");
        // driver = createOperaWebDriver(operaDriverPath, enableHeadlessMode);
        // break;
        case "remote":
            String seleniumHubHost = conf.get("selenium.hub.host", "localhost");
            int seleniumHubPort = Integer.parseInt(conf.get("selenium.hub.port", "4444"));
            String seleniumHubPath = conf.get("selenium.hub.path", "/wd/hub");
            String seleniumHubProtocol = conf.get("selenium.hub.protocol", "http");
            URL seleniumHubUrl = new URL(seleniumHubProtocol, seleniumHubHost, seleniumHubPort,
                    seleniumHubPath);

            String seleniumGridDriver = conf.get("selenium.grid.driver", "firefox");

            switch (seleniumGridDriver) {
            case "firefox":
                driver = createFirefoxRemoteWebDriver(seleniumHubUrl, enableHeadlessMode);
                break;
            case "chrome":
                driver = createChromeRemoteWebDriver(seleniumHubUrl, enableHeadlessMode);
                break;
            case "random":
                driver = createRandomRemoteWebDriver(seleniumHubUrl, enableHeadlessMode);
                break;
            default:
                LOG.error(
                        "The Selenium Grid WebDriver choice {} is not available... defaulting to FirefoxDriver().",
                        driverType);
                driver = createDefaultRemoteWebDriver(seleniumHubUrl, enableHeadlessMode);
                break;
            }
            break;
        default:
            LOG.error("The Selenium WebDriver choice {} is not available... defaulting to FirefoxDriver().",
                    driverType);
            FirefoxOptions options = new FirefoxOptions();
            driver = new FirefoxDriver(options);
            break;
        }
        LOG.debug("Selenium {} WebDriver selected.", driverType);

        driver.manage().timeouts().pageLoadTimeout(pageLoadWait, TimeUnit.SECONDS);
        driver.get(url);
    } catch (Exception e) {
        if (e instanceof TimeoutException) {
            LOG.error("Selenium WebDriver: Timeout Exception: Capturing whatever loaded so far...");
            return driver;
        } else {
            LOG.error(e.toString());
        }
        cleanUpDriver(driver);
        throw new RuntimeException(e);
    }

    return driver;
}

From source file:org.apache.nutch.protocol.webdriver.HttpWebClient.java

License:Apache License

public static String getHtmlPage(String url, Configuration conf) {
    WebDriver driver = null;

    try {/*  w  w  w  .j  a va2s  .  c  o m*/
        FirefoxProfile profile = new FirefoxProfile();
        String proxyHost = conf.get("http.proxy.host");
        int proxyPort = conf.getInt("http.proxy.port", 8080);
        if (proxyHost != null && proxyHost.length() > 0) {
            profile.setPreference("network.proxy.type", 1);
            profile.setPreference("network.proxy.http", proxyHost);
            profile.setPreference("network.proxy.http_port", proxyPort);
        }

        DesiredCapabilities capabilities = DesiredCapabilities.firefox();
        capabilities.setCapability("marionette", true);
        capabilities.setCapability("firefox_profile", profile);

        int driverServicePort = conf.getInt("webdriver.service.port", 4444);
        DriverService ds = NutchDriverService.createDriverService(driverServicePort);
        driver = new NutchFirefoxDriver(ds, capabilities);

        driver.get(url);
        // Wait for the page to load, timeout after 3 seconds
        new WebDriverWait(driver, 3);

        // Extract body
        String innerHtml = driver.findElement(By.tagName("body")).getAttribute("innerHTML");
        return innerHtml;
        // I'm sure this catch statement is a code smell ; borrowing it from
        // lib-htmlunit
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        if (driver != null)
            try {
                driver.quit();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
    }
}