Example usage for org.openqa.selenium.firefox FirefoxDriver navigate

List of usage examples for org.openqa.selenium.firefox FirefoxDriver navigate

Introduction

In this page you can find the example usage for org.openqa.selenium.firefox FirefoxDriver navigate.

Prototype

@Override
    public Navigation navigate() 

Source Link

Usage

From source file:com.coinbot.core.Worker.java

License:Open Source License

@Override
public void run() {
    File pathToBinary = new File("/home/jian/Descargas/firefox46/bin/firefox");
    // Firefox 46 needed
    FirefoxBinary ffBinary = new FirefoxBinary(pathToBinary);
    FirefoxProfile profile = new FirefoxProfile();
    FirefoxDriver driver = new FirefoxDriver(ffBinary, profile);
    CoinbotApplication.ui.workerQueue.addWorker(workerPanel);

    while (CoinbotApplication.bot.isRunning()) {
        // Sacamos un "claim" de la cola
        Claim claim = CoinbotApplication.bot.getClaimQueue().next();
        if (claim == null) {
            continue;
        }/*from  www. j  av a2  s  .  co m*/

        claim.getPanel().reset();
        claim.getPanel().getProgressBar().setMaximum(10);
        workerPanel.addClaim(claim.getPanel());
        claim.getPanel().nextStep("Opening URL");

        try {
            driver.manage().timeouts().pageLoadTimeout(12, TimeUnit.SECONDS);
            driver.navigate().to(new URL(claim.getFaucet().getUrl()));
        } catch (MalformedURLException e) {
            e.printStackTrace();
            continue;
        } catch (TimeoutException e) {
            // Busca un elemento, si no lo encuentra que vuelva a cargar
            e.printStackTrace();
        }

        // Detectando captcha
        claim.getPanel().nextStep("Detecting Captcha");
        CaptchaDetector captchaDetector = new CaptchaDetector();
        CaptchaService captcha = null;

        try {
            captcha = captchaDetector.find(driver, driver.findElement(By.tagName("body")));
        } catch (NoSuchElementException ex) {
            ex.printStackTrace();
            claim.getPanel().nextStep("Body not found!");
            continue;
        } catch (UnrecognizedCaptcha ex) {
            ex.printStackTrace();
            claim.getPanel().nextStep("Captcha not recognized.");
            continue;
        } catch (Exception ex) {
            continue;
        }

        claim.getPanel().nextStep("Trying auto resolving");
        // Intentamos buscar el hash en la DB 
        CaptchaHash ch = new CaptchaHash(captcha);
        String answer = CoinbotApplication.captchaDatabase.getAnswer(ch.getHash());

        // Si no enctramos la respuesta en la bd se la pedimos al usuario
        if (answer == null) {
            claim.getPanel().nextStep("Waiting for captcha answer ...");

            // Encolar captcha
            CoinbotApplication.bot.getCaptchaQueue().toQueue(captcha);

            // Esperar la resolucion del captcha
            CaptchaTimer timer = new CaptchaTimer(captcha, 35);
            timer.start();

            // Esperamos a la resolucion
            while (!timer.isExpired() && !captcha.resolved()) {
                CoinbotApplication.ui.captchaQueue.getCaptchaPanel(captcha).setTimer(timer.getSecondsLeft());
            }

            if (!captcha.resolved()) {
                CoinbotApplication.captchaDatabase.addCaptcha(ch);
                continue;
            }
        }

        // Guardamos el captcha en la DB
        CoinbotApplication.captchaDatabase.addCaptcha(new CaptchaHash(captcha));

        // Y la imagen en un archivo
        try {
            ImageIO.write(captcha.getImage(), "png", new File("coinbot/captchas/" + ch.getHash() + ".png"));
        } catch (IOException e) {
            e.printStackTrace();
        }

        // Envia la respuesta al input
        captcha.answerToInput(driver);

        // Desencolar captcha
        CoinbotApplication.bot.getCaptchaQueue().deQueue(captcha);

        // Escribir address
        claim.getPanel().nextStep("Detecting input address");
        InputAddressDetector iad = new InputAddressDetector(driver);
        iad.insertAddress(claim.getBtcAddress());

        //claim.getPanel().nextStep("Detecting Antibot");
        // Detectar antibot (puzzle no soportado)
        // Resolver antibot

        // submit
        claim.getPanel().nextStep("Submiting ...");
        WebElement submit = driver.findElement(By.id("address"));
        submit.submit();

        claim.getPanel().nextStep("Checking response");
        //claim.getPanel().nextStep("Successfull claim!");
        /*WebElement out = null;
                
        try {
           out = driver.findElement(By.className("alert-success"));
        } catch (NoSuchElementException e) {
                   
        }
                
        try {
           out = driver.findElement(By.className("alert-danger"));
        } catch (NoSuchElementException e) {
        }
        */
        //claim.getPanel().nextStep("Failed claim!");

        claim.getPanel().done();
        workerPanel.removeClaim(claim.getPanel());
        claim.getTimer().done(2000, 1);
        CoinbotApplication.bot.getClaimQueue().toQueue(claim);

        try {
            Thread.sleep(25000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    try {
        driver.close();
    } catch (Exception e) {

    }
    CoinbotApplication.ui.workerQueue.removeWorker(workerPanel);
    System.out.println("Worker " + workerId + " end work!");
}

From source file:com.vaadin.testbench.TestBenchDriverTest.java

@Test
public void testTestBenchDriverActsAsProxy() {
    FirefoxDriver mockDriver = createMock(FirefoxDriver.class);
    mockDriver.close();//from ww w .  j  ava2s. c o m
    expectLastCall().once();
    WebElement mockElement = createNiceMock(WebElement.class);
    expect(mockDriver.findElement(isA(By.class))).andReturn(mockElement);
    List<WebElement> elements = Arrays.asList(mockElement);
    expect(mockDriver.findElements(isA(By.class))).andReturn(elements);
    mockDriver.get("foo");
    expectLastCall().once();
    expect(mockDriver.getCurrentUrl()).andReturn("foo");
    expect(mockDriver.getPageSource()).andReturn("<html></html>");
    expect(mockDriver.getTitle()).andReturn("bar");
    expect(mockDriver.getWindowHandle()).andReturn("baz");
    Set<String> handles = new HashSet<String>();
    expect(mockDriver.getWindowHandles()).andReturn(handles);
    Options mockOptions = createNiceMock(Options.class);
    expect(mockDriver.manage()).andReturn(mockOptions);
    Navigation mockNavigation = createNiceMock(Navigation.class);
    expect(mockDriver.navigate()).andReturn(mockNavigation);
    mockDriver.quit();
    expectLastCall().once();
    expect(((JavascriptExecutor) mockDriver).executeScript(anyObject(String.class))).andStubReturn(true);
    TargetLocator mockTargetLocator = createNiceMock(TargetLocator.class);
    expect(mockDriver.switchTo()).andReturn(mockTargetLocator);
    replay(mockDriver);

    // TestBenchDriverProxy driver = new TestBenchDriverProxy(mockDriver);
    WebDriver driver = TestBench.createDriver(mockDriver);
    driver.close();
    By mockBy = createNiceMock(By.class);
    assertTrue(driver.findElement(mockBy) instanceof TestBenchElementCommands);
    assertTrue(driver.findElements(mockBy).get(0) instanceof TestBenchElementCommands);
    driver.get("foo");
    assertEquals("foo", driver.getCurrentUrl());
    assertEquals("<html></html>", driver.getPageSource());
    assertEquals("bar", driver.getTitle());
    assertEquals("baz", driver.getWindowHandle());
    assertEquals(handles, driver.getWindowHandles());
    assertEquals(mockOptions, driver.manage());
    assertEquals(mockNavigation, driver.navigate());
    driver.quit();
    assertEquals(mockTargetLocator, driver.switchTo());

    verify(mockDriver);
}

From source file:NCB.Extractor.java

public static void idextractor(FirefoxDriver driver) {
    try {//from  ww w. j ava2 s .  com
        String src = null;
        db = new DBActivityMInsLM();
        stUpdte = db.con.createStatement();

        ResultSet count = stUpdte.executeQuery("select * from NCB_Linkids where status=0");

        while (count.next()) {
            strInputid = count.getString("Link");

            System.out.println(strInputid);
            driver.navigate().to(strInputid);
            Thread.sleep(2000);
            src = driver.getPageSource().toString();
            Thread.sleep(3000);
            extractData(src, strInputid);
            String q = "update NCB_Linkids set Status=1 where Link='" + strInputid + "'";
            System.out.println(q);
            stUpdte = db.con.createStatement();
            stUpdte.executeUpdate(q);
            stUpdte.close();

        }
        stmtdelete.executeUpdate("Truncate NCB_Linkids");
        stmtdelete.close();
        db.closeDB();
        driver.close();

    } catch (Exception e) {
        System.out.println("Error in idextraction" + e);
    }

}

From source file:org.ado.picasa.Main.java

License:Apache License

public static void main(String[] args) throws Exception {
    final Options options = new Options();
    options.addOption(new Option("a", "album", true, "Album name"));
    options.addOption("v", "verification-code", true, "Verification code");
    options.addOption("o", "output", true, "Albums output directory");
    options.addOption("h", "help", false, "Prints this help");
    final CommandLine cmd = new DefaultParser().parse(options, args);

    if (cmd.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("picasa-crawler", options);
        System.exit(0);//from  w w  w.  j  a  v  a 2  s .c om
    }

    validateEnvironmentVariables();
    final File outputDirectory;
    if (cmd.hasOption("o")) {
        outputDirectory = new File(cmd.getOptionValue("o"));
    } else {
        outputDirectory = DEFAULT_OUTPUT_DIR;
    }
    FileUtils.forceMkdir(outputDirectory);
    long start = System.currentTimeMillis();

    final FirefoxProfile profile = new FirefoxProfile();
    profile.setPreference("browser.download.folderList", 2);
    profile.setPreference("browser.download.dir", outputDirectory.getAbsolutePath());
    profile.setPreference("browser.helperApps.neverAsk.saveToDisk", "image/jpeg,image/png");
    final FirefoxDriver driver = new FirefoxDriver(profile);
    loginIntoPicasa(cmd.getOptionValue("v"), driver);

    driver.navigate().to("https://picasaweb.google.com/home?showall=true");
    TimeUnit.SECONDS.sleep(2);

    final List<WebElement> albumLinks = driver
            .findElements(By.xpath("//p[@class='gphoto-album-cover-title']/a"));

    if (cmd.hasOption("a")) {
        final String albumName = cmd.getOptionValue("a").trim();
        System.out.println(String.format("Album: %s", albumName));
        downloadAlbum(driver, albumLinks.stream().filter(al -> al.getText().equals(albumName)).findFirst().get()
                .getAttribute("href"), outputDirectory);

    } else {

        final Set<String> albumHrefs = albumLinks.stream().map(a -> a.getAttribute("href"))
                .collect(Collectors.toSet());

        albumHrefs.forEach(a -> downloadAlbum(driver, a, outputDirectory));

    }
    TimeUnit.SECONDS.sleep(10);
    System.out.println("done");
    long end = System.currentTimeMillis();
    System.out.println(String.format("execution took %d minutes.",
            Math.min(TimeUnit.MILLISECONDS.toMinutes(end - start), 1)));
    driver.close();
}

From source file:org.ado.picasa.Main.java

License:Apache License

private static void downloadAlbum(FirefoxDriver driver, String album, File outputDir) {
    try {//ww w  .j  av a  2  s  .  c  om
        final String albumName = getAlbumName(album);
        System.out.println(String.format("> album name: %s  url: %s", albumName, album));
        driver.navigate().to(album);

        final List<String> photoHrefLinks = driver.findElements(By.xpath("//div[@class='goog-icon-list']//a"))
                .stream().filter(a -> MediaType.PHOTO.equals(getMediaType(a))).map(a -> a.getAttribute("href"))
                .collect(Collectors.toList());

        for (String href : photoHrefLinks) {
            downloadPhoto(driver, href);
        }

        driver.navigate().to(album);

        final List<String> videoHrefLinks = driver.findElements(By.xpath("//div[@class='goog-icon-list']//a"))
                .stream().filter(a -> MediaType.VIDEO.equals(getMediaType(a))).map(a -> a.getAttribute("href"))
                .collect(Collectors.toList());

        int index = 1;
        final FileDownloader fileDownloader = new FileDownloader(driver, outputDir.getAbsolutePath());
        for (String videoUrl : getVideoUrls(driver, videoHrefLinks, album)) {
            try {
                new FileHandler(fileDownloader.downloader(videoUrl, albumName + index++ + ".m4v"));
            } catch (Exception e) {
                System.err.println(String.format("Cannot download video '%s'.", videoUrl));
                e.printStackTrace();
            }
        }

        TimeUnit.SECONDS.sleep(10);
        System.out.println(String.format("moving photos to directory: %s", albumName));
        final File albumDirectory = new File(outputDir, albumName);
        for (File file : FileUtils.listFiles(outputDir, null, false)) {
            try {
                FileUtils.moveFileToDirectory(file, albumDirectory, true);
            } catch (IOException e) {
                FileUtils.moveFile(file,
                        new File(albumDirectory, file.getName() + "-" + System.currentTimeMillis()));
            }
        }
    } catch (Exception e) {
        System.err.println(String.format("Cannot download album '%s'", album));
        e.printStackTrace();
    }
}

From source file:org.ado.picasa.Main.java

License:Apache License

private static List<String> getVideoUrls(FirefoxDriver driver, List<String> videoHrefLinks, String returnPage) {
    final List<String> urls = new ArrayList<>();
    for (String href : videoHrefLinks) {
        System.out.println(String.format("downloading video: %s", href));
        try {// w w w.ja  va 2  s  .co  m
            driver.navigate().to(href);
            TimeUnit.SECONDS.sleep(1);

            driver.switchTo().frame(driver.findElementByXPath("//iframe[@class='scaledimage-onscreenpane']"));
            urls.add(driver.findElementByXPath("//video").getAttribute("src"));

        } catch (Exception e) {
            System.err.println(String.format("Cannot get video url from '%s'. Skipping ...", href));
            e.printStackTrace();
        } finally {
            driver.navigate().to(returnPage);
        }
    }
    return urls;
}

From source file:org.ado.picasa.Main.java

License:Apache License

private static void downloadPhoto(FirefoxDriver driver, String href) {
    try {/*from   w  w  w .j  a  va2s.  c o m*/
        driver.navigate().to(href);
        TimeUnit.SECONDS.sleep(1);

        driver.executeScript(
                "document.getElementsByClassName('goog-inline-block goog-toolbar-menu-button')[2].style['display']=''");
        driver.findElement(By.xpath("//div[@class='goog-inline-block goog-toolbar-menu-button'][3]")).click();
        TimeUnit.MILLISECONDS.sleep(200);
        driver.findElement(By.xpath("//div[@role='menu']")).click();
    } catch (Exception e) {
        System.err.println(String.format("Cannot download photo on '%s'. Skipping ...", href));
        e.printStackTrace();
    }
}