Example usage for org.openqa.selenium WebDriver getWindowHandle

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

Introduction

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

Prototype

String getWindowHandle();

Source Link

Document

Return an opaque handle to this window that uniquely identifies it within this driver instance.

Usage

From source file:browsermator.com.NextTabAction.java

@Override
public void RunAction(WebDriver driver) {
    try {/*from w  ww.ja va2s .  com*/
        //       Actions actions = new Actions(driver);
        String current_tab_handle = driver.getWindowHandle();

        driver.findElement(By.cssSelector("body")).sendKeys(Keys.chord(Keys.CONTROL, Keys.TAB));
        // actions.keyDown(Keys.CONTROL).sendKeys(Keys.TAB).keyUp(Keys.CONTROL).build().perform();

        Set<String> tab_handles = driver.getWindowHandles();
        int current_tab_index = 0;

        int number_of_tabs = tab_handles.size();
        int tabs_counted = 1;
        for (String handle : tab_handles) {
            if (handle.equals(current_tab_handle)) {

                if (tabs_counted == number_of_tabs) {
                    // last tab
                    current_tab_index = 0;
                } else {
                    current_tab_index = tabs_counted;
                }
            }

            tabs_counted++;
        }

        driver.switchTo().window(tab_handles.toArray()[current_tab_index].toString());

        this.Pass = true;
    } catch (Exception ex) {
        this.Pass = false;
    }
}

From source file:businesscomponents.ReportCompare1.java

public static void main(String[] args) throws InterruptedException {
    // TODO Auto-generated method stub

    WebDriver driver = new FirefoxDriver();
    driver.get("http://148.173.174.122:8900/acadmin/?serverURL=http://wpqwa551:8000");
    driver.manage().window().maximize();

    String strUserName = "kgoutham";
    String strPassWord = "kgoutham";

    driver.findElement(By.name("userID")).clear();
    driver.findElement(By.name("userID")).sendKeys(strUserName);
    driver.findElement(By.name("Password")).clear();
    driver.findElement(By.name("Password")).sendKeys(strPassWord);

    driver.findElement(By.name("loginBtn")).click();
    Thread.sleep(1200);//  w  ww. j av  a  2 s. c om
    System.out.println("Page title is: " + driver.getTitle());

    if (driver.getTitle().contains("Files & Folders")) {
        driver.findElement(By.id("Jobs")).click();
        Thread.sleep(2500);
        driver.switchTo().defaultContent();
        WebElement frame = driver.findElement(By.id("TableFrame"));
        driver.switchTo().frame(frame);
        Thread.sleep(1200);
        if (driver.findElement(By.xpath("//a[contains(@onmouseover,'completedjobs')]")).isDisplayed()) {
            try {
                JavascriptExecutor executor = (JavascriptExecutor) driver;
                executor.executeScript("arguments[0].click();",
                        driver.findElement(By.xpath("//a[contains(@onmouseover,'completedjobs')]")));
            } catch (Exception e) {
                driver.findElement(By.xpath("//a[contains(@onmouseover,'completedjobs')]")).click();
            }

            System.out.println("Clicking on Completed Tabs");
        } else {
            System.out.println("Failed:Unable to Find the Completed Tab section");
        }
        Thread.sleep(1200);
        WebElement frame1 = driver.findElement(By.id("TableFrame"));
        driver.switchTo().frame(frame1);
        String strValue = "MRF412";
        driver.findElement(By.id("FilterText")).clear();
        driver.findElement(By.id("FilterText")).sendKeys(strValue);
        Thread.sleep(1200);
        driver.findElement(By.xpath("//input[@value='Apply']")).click();
        Thread.sleep(3500);
        WebElement frame2 = driver.findElement(By.id("ifrListFrame"));
        driver.switchTo().frame(frame2);

        if (driver.findElement(By.xpath("(//a[contains(text(),'MRF412_reportcheck.ROI')])[1]")).isDisplayed()) {

            String oldTab = driver.getWindowHandle();
            driver.findElement(By.xpath("(//a[contains(text(),'MRF412_reportcheck.ROI')])[1]")).click();
            Thread.sleep(5000);
            ArrayList<String> newTab = new ArrayList<String>(driver.getWindowHandles());
            newTab.remove(oldTab);
            // change focus to new tab
            driver.switchTo().window(newTab.get(0));
            WebElement frame3 = driver.findElement(By.id("reportframe"));
            driver.switchTo().frame(frame3);
            String strPageSource = driver.getPageSource();
            CommonData.strPageSource = strPageSource;
            String strPageTitle = driver.findElement(By.xpath("//div[contains(@id,'water')]")).getText();
            CommonData.strPageTitle = strPageTitle;

            if (strPageTitle.contains("MultiUserTest License")) {
                System.out.println("Verifying the MultiUserTest License page is displayed");
                List<WebElement> products = driver
                        .findElements(By.xpath("//div[contains(@onmouseover,'Partner Name')]"));
                ArrayList<String> strPartnerName = CommonData.strPartnerName;
                ArrayList<String> strInvoiceNumber = CommonData.strInvoiceNumber;
                ArrayList<String> strTotalPayment = CommonData.strTotalPayment;
                ArrayList<String> strSENumber = CommonData.strSENumber;
                ArrayList<String> strPaymentMarket = CommonData.strPaymentMarket;
                ArrayList<String> strPaymentunit = CommonData.strPaymentunit;
                ArrayList<String> strLiabilityUnit = CommonData.strLiabilityUnit;
                ArrayList<String> strLiabilityCurrency = CommonData.strLiabilityCurrency;
                ArrayList<String> strMarketCurrency = CommonData.strMarketCurrency;
                ArrayList<String> strInvoiceReleaseDate = CommonData.strInvoiceReleaseDate;
                ArrayList<String> strUserId = CommonData.strUserId;

                for (int i = 1; i <= products.size(); i++) {
                    System.out.println(
                            "-----------------DISPLAYING LIST OF TABLE VALUES----------------------->: " + i);
                    String strPartnerNameList = driver
                            .findElement(By.xpath("(//div[contains(@onmouseover,'Partner Name')])[" + i + "]"))
                            .getText();
                    strPartnerName.add(strPartnerNameList);
                    System.out.println("Displaying the Partner Name list :" + strPartnerNameList);
                    String strInvoiceNumberList = driver
                            .findElement(
                                    By.xpath("(//div[contains(@onmouseover,'Invoice Number')])[" + i + "]"))
                            .getText();
                    strInvoiceNumber.add(strInvoiceNumberList);
                    System.out.println("Displaying the Invoice Number list :" + strInvoiceNumberList);
                    String strTotalPaymentList;
                    if (i > 1) {
                        int j;
                        if (i == 3) {
                            j = i + 2;
                        } else {
                            j = i + 1;
                        }

                        strTotalPaymentList = driver
                                .findElement(
                                        By.xpath("(//div[contains(@onmouseover,'Total Payment')])[" + j + "]"))
                                .getText();
                    } else {
                        strTotalPaymentList = driver
                                .findElement(
                                        By.xpath("(//div[contains(@onmouseover,'Total Payment')])[" + i + "]"))
                                .getText();
                    }
                    strTotalPayment.add(strTotalPaymentList);
                    System.out.println("Displaying the Total Payment list :" + strTotalPaymentList);
                    String strSENumberList = driver
                            .findElement(By.xpath("(//div[contains(@onmouseover,'SE Number')])[" + i + "]"))
                            .getText();
                    strSENumber.add(strSENumberList);
                    System.out.println("Displaying the SE Number list :" + strSENumberList);
                    String strPaymentMarketList = driver
                            .findElement(
                                    By.xpath("(//div[contains(@onmouseover,'Payment Market')])[" + i + "]"))
                            .getText();
                    strPaymentMarket.add(strPaymentMarketList);
                    System.out.println("Displaying the Payment Market list :" + strPaymentMarketList);
                    String strPaymentUnitList = driver
                            .findElement(By.xpath("(//div[contains(@onmouseover,'Payment Unit')])[" + i + "]"))
                            .getText();
                    strPaymentunit.add(strPaymentUnitList);
                    System.out.println("Displaying the Payment Unit list :" + strPaymentUnitList);
                    String strLiabilityUnitList = driver
                            .findElement(
                                    By.xpath("(//div[contains(@onmouseover,'Liability Unit')])[" + i + "]"))
                            .getText();
                    strLiabilityUnit.add(strLiabilityUnitList);
                    System.out.println("Displaying the Liability Unit list :" + strLiabilityUnitList);
                    String strLiabilityCurrencyList = driver
                            .findElement(
                                    By.xpath("(//div[contains(@onmouseover,'Liability Currency')])[" + i + "]"))
                            .getText();
                    strLiabilityCurrency.add(strLiabilityCurrencyList);
                    System.out.println("Displaying the Liability Currency list :" + strLiabilityCurrencyList);
                    String strMarketCurrencyList = driver
                            .findElement(
                                    By.xpath("(//div[contains(@onmouseover,'Market Currency')])[" + i + "]"))
                            .getText();
                    strMarketCurrency.add(strMarketCurrencyList);
                    System.out.println("Displaying the Market Currency list :" + strMarketCurrencyList);
                    String strInvoiceReleaseDateList;
                    if (i > 1) {
                        int j;
                        if (i == 3) {
                            j = i + 2;
                        } else {
                            j = i + 1;
                        }

                        strInvoiceReleaseDateList = driver.findElement(By.xpath(
                                "(//div[contains(@onmouseover,'This is the difference in cost between Invoice Total and Market Totals')]/nobr)["
                                        + j + "]"))
                                .getText();
                    } else {
                        strInvoiceReleaseDateList = driver.findElement(By.xpath(
                                "(//div[contains(@onmouseover,'This is the difference in cost between Invoice Total and Market Totals')]/nobr)["
                                        + i + "]"))
                                .getText();
                    }
                    strInvoiceReleaseDate.add(strInvoiceReleaseDateList);
                    System.out
                            .println("Displaying the Invoice release date list :" + strInvoiceReleaseDateList);
                    String strUserIDList = driver
                            .findElement(By.xpath("(//div[contains(@onmouseover,'USER ID')])[" + i + "]"))
                            .getText();
                    strUserId.add(strUserIDList);
                    System.out.println("Displaying the UserId list :" + strUserIDList);
                }
                //               for (int i = 0; i < products.size(); i++) {
                //                  System.out.println("############ CHECKING ########################");
                //                  System.out.println(CommonData.strInvoiceNumber.get(i) + " Invoice Number");
                //                  System.out.println(CommonData.strInvoiceReleaseDate.get(i) + " Invoice Release Date");
                //                  System.out.println(CommonData.strTotalPayment.get(i) + " Total Payment");
                //
                //               }
            } else {
                System.out.println("MultiUserTest License is not displayed");
            }

            driver.switchTo().defaultContent();
            driver.close();
            driver.switchTo().window(oldTab);
            // driver.get("
            // http://148.173.174.122:8900/acadmin/?serverURL=http://wpqwa551:8000");
            driver.get(
                    "http://148.173.174.122:8900/acadmin/jobmanager.jsp?serverURL=http%3a%2f%2fwpqwa551%3a8000&volume=wpqwa551&daemonURL=http://wpqwa551:8100&daemonURL=http://wpqwa551:8100");

            if (driver.findElement(By.xpath("//td[contains(text(),'System')]")).isDisplayed()) {
                System.out.println("--------------##### Focus Changed to old window #### -----------");
            } else {
                System.out.println("---------Focus not changed---------------");
            }
            driver.switchTo().defaultContent();
            WebElement postframe = driver.findElement(By.id("TableFrame"));
            driver.switchTo().frame(postframe);
            Thread.sleep(1200);
            if (driver.findElement(By.xpath("//a[contains(@onmouseover,'completedjobs')]")).isDisplayed()) {
                try {
                    JavascriptExecutor executor = (JavascriptExecutor) driver;
                    executor.executeScript("arguments[0].click();",
                            driver.findElement(By.xpath("//a[contains(@onmouseover,'completedjobs')]")));
                } catch (Exception e) {
                    driver.findElement(By.xpath("//a[contains(@onmouseover,'completedjobs')]")).click();
                }
                System.out.println("Clicking on Completed Tabs");
            } else {
                System.out.println("Failed:Unable to Find the Completed Tab section");
            }
            Thread.sleep(5000);
            WebElement postframe1 = driver.findElement(By.id("TableFrame"));
            driver.switchTo().frame(postframe1);
            String strPostValue = "MRF412";
            driver.findElement(By.id("FilterText")).clear();
            driver.findElement(By.id("FilterText")).sendKeys(strPostValue);
            Thread.sleep(1200);
            driver.findElement(By.xpath("//input[@value='Apply']")).click();
            Thread.sleep(3500);
            WebElement postframe2 = driver.findElement(By.id("ifrListFrame"));
            driver.switchTo().frame(postframe2);
            String postoldTab = driver.getWindowHandle();
            driver.findElement(By.xpath("(//a[contains(text(),'MRF412_reportcheck.ROI')])[1]")).click();
            Thread.sleep(5000);
            ArrayList<String> newTab_1 = new ArrayList<String>(driver.getWindowHandles());
            newTab_1.remove(postoldTab);
            // change focus to new tab
            driver.switchTo().window(newTab_1.get(0));
            WebElement postframe3 = driver.findElement(By.id("reportframe"));
            driver.switchTo().frame(postframe3);
            System.out.println("-############## COMPARING PRE-REPORT and POST-REPORT-##############--");
            // String strPostPageSource = driver.getPageSource();
            String strPostPageTitle = driver.findElement(By.xpath("//div[contains(@id,'water')]")).getText();
            if (strPostPageTitle.contains(CommonData.strPageTitle)) {
                System.out.println(
                        "Passed : Page Title is matching with Pre-report and Post-Report " + strPostPageTitle);

                for (int i = 1, k = 0; i <= CommonData.strPartnerName.size(); i++, k++) {
                    System.out.println(
                            "----------------->>>  COMPARING LIST OF TABLE VALUES FORM PRE-REPORT AND POST-REPORT  ----------------------->>>: "
                                    + i);
                    String strPostPartnerNameList = driver
                            .findElement(By.xpath("(//div[contains(@onmouseover,'Partner Name')])[" + i + "]"))
                            .getText();
                    if (CommonData.strPartnerName.get(k).contains(strPostPartnerNameList)) {
                        System.out.println("Passed : Partner Name is matching with Pre-report and Post-Report :"
                                + strPostPartnerNameList);
                    } else {
                        System.out.println(
                                "Failed : Partner Name is not matching with Pre-report and Post-Report :"
                                        + strPostPartnerNameList);
                    }

                    String strPostInvoiceNumberList = driver
                            .findElement(
                                    By.xpath("(//div[contains(@onmouseover,'Invoice Number')])[" + i + "]"))
                            .getText();
                    if (CommonData.strInvoiceNumber.get(k).contains(strPostInvoiceNumberList)) {
                        System.out.println(
                                "Passed : Post Invoice Number is matching with Pre-report and Post-Report :"
                                        + strPostInvoiceNumberList);
                    } else {
                        System.out.println(
                                "Failed : Post Invoice Number is not matching with Pre-report and Post-Report :"
                                        + strPostInvoiceNumberList);
                    }

                    String strPostTotalPaymentList;
                    if (i > 1) {
                        int j;
                        if (i == 3) {
                            j = i + 2;
                        } else {
                            j = i + 1;
                        }

                        strPostTotalPaymentList = driver
                                .findElement(
                                        By.xpath("(//div[contains(@onmouseover,'Total Payment')])[" + j + "]"))
                                .getText();
                        if (CommonData.strTotalPayment.get(k).contains(strPostTotalPaymentList)) {
                            System.out.println(
                                    "Passed : Total Payment List is matching with Pre-report and Post-Report :"
                                            + strPostTotalPaymentList);
                        } else {
                            System.out.println(
                                    "Failed : Total Payment List is not matching with Pre-report and Post-Report :"
                                            + strPostTotalPaymentList);
                        }
                    } else {
                        strPostTotalPaymentList = driver
                                .findElement(
                                        By.xpath("(//div[contains(@onmouseover,'Total Payment')])[" + i + "]"))
                                .getText();
                        if (CommonData.strTotalPayment.get(k).contains(strPostTotalPaymentList)) {
                            System.out.println(
                                    "Passed : Total Payment List is matching with Pre-report and Post-Report :"
                                            + strPostTotalPaymentList);
                        } else {
                            System.out.println(
                                    "Failed : Total Payment List is not matching with Pre-report and Post-Report :"
                                            + strPostTotalPaymentList);
                        }
                    }

                    String strPostSENumberList = driver
                            .findElement(By.xpath("(//div[contains(@onmouseover,'SE Number')])[" + i + "]"))
                            .getText();

                    if (CommonData.strSENumber.get(k).contains(strPostSENumberList)) {
                        System.out
                                .println("Passed : SE Number List is matching with Pre-report and Post-Report :"
                                        + strPostSENumberList);
                    } else {
                        System.out.println(
                                "Failed : SE Number List is not matching with Pre-report and Post-Report :"
                                        + strPostSENumberList);
                    }

                    String strPostPaymentMarketList = driver
                            .findElement(
                                    By.xpath("(//div[contains(@onmouseover,'Payment Market')])[" + i + "]"))
                            .getText();

                    if (CommonData.strPaymentMarket.get(k).contains(strPostPaymentMarketList)) {
                        System.out
                                .println("Passed : Payment Market is matching with Pre-report and Post-Report :"
                                        + strPostPaymentMarketList);
                    } else {
                        System.out.println(
                                "Failed : Payment Market is not matching with Pre-report and Post-Report :"
                                        + strPostPaymentMarketList);
                    }

                    String strPostPaymentUnitList = driver
                            .findElement(By.xpath("(//div[contains(@onmouseover,'Payment Unit')])[" + i + "]"))
                            .getText();
                    if (CommonData.strPaymentunit.get(k).contains(strPostPaymentUnitList)) {
                        System.out.println(
                                "Passed : Payment Unit list is matching with Pre-report and Post-Report :"
                                        + strPostPaymentUnitList);
                    } else {
                        System.out.println(
                                "Failed : Payment Unit list is not matching with Pre-report and Post-Report :"
                                        + strPostPaymentUnitList);
                    }

                    String strPostLiabilityUnitList = driver
                            .findElement(
                                    By.xpath("(//div[contains(@onmouseover,'Liability Unit')])[" + i + "]"))
                            .getText();
                    if (CommonData.strLiabilityUnit.get(k).contains(strPostLiabilityUnitList)) {
                        System.out.println(
                                "Passed : Liability Unit list is matching with Pre-report and Post-Report :"
                                        + strPostLiabilityUnitList);
                    } else {
                        System.out.println(
                                "Failed : Liability Unit list is not matching with Pre-report and Post-Report :"
                                        + strPostLiabilityUnitList);
                    }

                    String strPostLiabilityCurrencyList = driver
                            .findElement(
                                    By.xpath("(//div[contains(@onmouseover,'Liability Currency')])[" + i + "]"))
                            .getText();
                    if (CommonData.strLiabilityCurrency.get(k).contains(strPostLiabilityCurrencyList)) {
                        System.out.println(
                                "Passed : Liability Currency list is matching with Pre-report and Post-Report :"
                                        + strPostLiabilityCurrencyList);
                    } else {
                        System.out.println(
                                "Failed : Liability Currency list is not matching with Pre-report and Post-Report :"
                                        + strPostLiabilityCurrencyList);
                    }

                    String strPostMarketCurrencyList = driver
                            .findElement(
                                    By.xpath("(//div[contains(@onmouseover,'Market Currency')])[" + i + "]"))
                            .getText();
                    if (CommonData.strMarketCurrency.get(k).contains(strPostMarketCurrencyList)) {
                        System.out.println(
                                "Passed : Market Currency list is matching with Pre-report and Post-Report :"
                                        + strPostMarketCurrencyList);
                    } else {
                        System.out.println(
                                "Failed : Market Currency list is not matching with Pre-report and Post-Report :"
                                        + strPostMarketCurrencyList);
                    }

                    String strPostInvoiceReleaseDateList;
                    if (i > 1) {
                        int j;
                        if (i == 3) {
                            j = i + 2;
                        } else {
                            j = i + 1;
                        }

                        strPostInvoiceReleaseDateList = driver.findElement(By.xpath(
                                "(//div[contains(@onmouseover,'This is the difference in cost between Invoice Total and Market Totals')]/nobr)["
                                        + j + "]"))
                                .getText();
                        if (CommonData.strInvoiceReleaseDate.get(k).contains(strPostInvoiceReleaseDateList)) {
                            System.out.println(
                                    "Passed : Invoice Release Date list is matching with Pre-report and Post-Report :"
                                            + strPostInvoiceReleaseDateList);
                        } else {
                            System.out.println(
                                    "Failed : Invoice Release Date list is not matching with Pre-report and Post-Report :"
                                            + strPostInvoiceReleaseDateList);
                        }
                    } else {
                        strPostInvoiceReleaseDateList = driver.findElement(By.xpath(
                                "(//div[contains(@onmouseover,'This is the difference in cost between Invoice Total and Market Totals')]/nobr)["
                                        + i + "]"))
                                .getText();
                        if (CommonData.strInvoiceReleaseDate.get(k).contains(strPostInvoiceReleaseDateList)) {
                            System.out.println(
                                    "Passed : Invoice Release Date list is matching with Pre-report and Post-Report :"
                                            + strPostInvoiceReleaseDateList);
                        } else {
                            System.out.println(
                                    "Failed : Invoice Release Date list is not matching with Pre-report and Post-Report :"
                                            + strPostInvoiceReleaseDateList);
                        }
                    }

                    String strPostUserIDList = driver
                            .findElement(By.xpath("(//div[contains(@onmouseover,'USER ID')])[" + i + "]"))
                            .getText();
                    if (CommonData.strUserId.get(k).contains(strPostUserIDList)) {
                        System.out.println("Passed : User ID list is matching with Pre-report and Post-Report :"
                                + strPostUserIDList);
                    } else {
                        System.out.println(
                                "Failed : User ID list is not matching with Pre-report and Post-Report :"
                                        + strPostUserIDList);
                    }

                }
                driver.switchTo().defaultContent();
                driver.close();
                driver.switchTo().window(postoldTab);
                System.out.println(
                        "########################## COMPLETED VALIDATIONS ALL ARE MATCHING ##################################");
            } else {
                System.out.println("Failed : Page Title is not matching with Pre-report and Post-Report");
            }

        } else {
            System.out.println("Failed to open the Multi user license page");
        }

    } else {
        System.out.println("Unable to open the Files and folder page after login");
    }
    driver.quit();
}

From source file:cn.edu.hfut.dmic.webcollector.example.FirefoxSelenium3.java

License:Open Source License

public static void main(String[] args) throws Exception {
    Executor executor = new Executor() {
        @Override/*  ww  w.  jav  a 2  s .co  m*/
        public void execute(CrawlDatum datum, CrawlDatums next) throws Exception {
            MongoClient mongoClient = new MongoClient("localhost", 27017);
            // ?
            // DBCollection dbCollection = mongoClient.getDB("maoyan_crawler").getCollection("rankings_am"); 
            DB db = mongoClient.getDB("maoyan_crawler");
            // ?????
            Set<String> colls = db.getCollectionNames();
            for (String s : colls) {
                // Collection(?"")
                if (s.equals("attend_rate")) {
                    db.getCollection(s).drop();
                }
            }
            DBCollection dbCollection = db.getCollection("attend_rate");
            ProfilesIni pi = new ProfilesIni();
            FirefoxProfile profile = pi.getProfile("default");
            WebDriver driver = new FirefoxDriver(profile);
            driver.manage().window().maximize();
            driver.manage().timeouts().pageLoadTimeout(3, TimeUnit.SECONDS);
            //                driver.setJavascriptEnabled(false);
            driver.get(datum.getUrl());
            //                System.out.println(driver.getPageSource());
            driver.findElement(By.xpath("//*[@id='seat_city']")).click();
            driver.switchTo().window(driver.getWindowHandle());

            int city_num = driver.findElements(By.xpath("//div[@id='all-citys']/div/ul/li/a")).size();
            for (int i = 0; i < city_num; i++) {
                System.out.println("A city chosen" + i);
                System.out.println(
                        driver.findElements(By.xpath("//div[@id='all-citys']/div/ul/li/a")).get(i).getText());
                String city = driver.findElements(By.xpath("//div[@id='all-citys']/div/ul/li/a")).get(i)
                        .getText();
                ((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);",
                        driver.findElements(By.xpath("//div[@id='all-citys']/div/ul/li/a")).get(i));
                ((JavascriptExecutor) driver).executeScript("window.scrollBy(0, -250)", "");
                Thread.sleep(1000);
                new Actions(driver)
                        .moveToElement(
                                driver.findElements(By.xpath("//div[@id='all-citys']/div/ul/li/a")).get(i))
                        .click().perform();
                driver.switchTo().window(driver.getWindowHandle());
                //                System.out.println(driver.findElement(By.xpath("//span[@class='today']/em")).getText());
                System.out.println(driver.findElement(By.xpath("//span[@class='today']")).getText());
                for (int j = 0; j < driver
                        .findElements(By.xpath("//div[@id='seat_table']//ul//li[@class='c1 lineDot']"))
                        .size(); j++) {
                    System.out.println(driver
                            .findElements(By.xpath("//div[@id='seat_table']//ul//li[@class='c1 lineDot']"))
                            .get(j).getText());
                    System.out.println(
                            driver.findElements(By.xpath("//div[@id='seat_table']//ul//li[@class='c2 red']"))
                                    .get(j).getText());
                    System.out.println(
                            driver.findElements(By.xpath("//div[@id='seat_table']//ul//li[@class='c3 gray']"))
                                    .get(j).getText());
                    BasicDBObject dbObject = new BasicDBObject();
                    dbObject.append("title", driver.findElement(By.xpath("//span[@class='today']")).getText())
                            .append("city", city)
                            .append("mov_cnname",
                                    driver.findElements(
                                            By.xpath("//div[@id='seat_table']//ul//li[@class='c1 lineDot']"))
                                            .get(j).getText())
                            .append("boxoffice_rate", driver
                                    .findElements(By.xpath("//div[@id='seat_table']//ul//li[@class='c2 red']"))
                                    .get(j).getText())
                            .append("visit_pershow", driver
                                    .findElements(By.xpath("//div[@id='seat_table']//ul//li[@class='c3 gray']"))
                                    .get(j).getText());
                    dbCollection.insert(dbObject);
                }
                System.out.println("new city list to choose");
                new Actions(driver).moveToElement(driver.findElement(By.xpath("//*[@id='seat_city']"))).click()
                        .perform();
                driver.switchTo().window(driver.getWindowHandle());
                Thread.sleep(500);
            }
            driver.close();
            driver.quit();
            mongoClient.close();
        }
    };

    //DBDBManager
    DBManager manager = new BerkeleyDBManager("crawl");
    //Crawler?DBManagerExecutor
    Crawler crawler = new Crawler(manager, executor);
    crawler.addSeed("http://pf.maoyan.com/attend/rate");
    crawler.start(1);
}

From source file:com.comcast.magicwand.drivers.AbstractPhoenixDriver.java

License:Apache License

/**
 * {@inheritDoc}/*from   w  w w  .ja va2  s .  c o  m*/
 */
public String getWindowHandle() {
    WebDriver driver = this.getDriver();
    String windowHandle = null;

    if (null != driver) {
        windowHandle = driver.getWindowHandle();
    }

    return windowHandle;
}

From source file:com.dhenton9000.selenium.generic.BaseTest.java

protected boolean isAlertPresent(WebDriver driver) {
    boolean isAlertPresent = true;
    String oldWindow = driver.getWindowHandle();
    try {//from  w ww.  jav  a2 s.co m
        driver.switchTo().alert();
    } catch (NoAlertPresentException err) {
        return false;
    }
    driver.switchTo().window(oldWindow);
    return isAlertPresent;
}

From source file:com.evidon.areweprivateyet.Crawler.java

License:Open Source License

public Crawler(String namedProfile) throws Exception {
    loadSiteList();/*w w w.  j av  a 2  s .  c o  m*/

    int sleepTime = (namedProfile.equals("baseline") ? 10 : 5);
    boolean started = false;
    String baseWindow = "";

    FirefoxProfile profile = new ProfilesIni().getProfile(namedProfile);
    //profile.setPreference("webdriver.load.strategy", "fast");

    WebDriver driver = new FirefoxDriver(profile);

    driver.manage().timeouts().implicitlyWait(40, TimeUnit.SECONDS);
    driver.manage().timeouts().pageLoadTimeout(40, TimeUnit.SECONDS);
    driver.manage().timeouts().setScriptTimeout(40, TimeUnit.SECONDS);

    // figure out where the fucking profile is. wow!
    String profileDir = getDriverProfile();

    log("Crawling started for " + namedProfile);

    int count = 0;
    for (String url : urls) {
        if (!started) {
            // Original window handle to be used as base. Used so we can close all other popups.  
            baseWindow = driver.getWindowHandle();
            started = true;
        }

        count++;
        log("\t" + count + ". navigating to: " + url);

        CrawlusInterruptus ci = new CrawlusInterruptus(60);
        try {
            ci.start();

            try {
                // Confirm handling for one of those super fucking annoying "Are you sure you wonna go anywhere else?"
                driver.switchTo().alert().accept();
                log("\tAccepted a navigate away modal");
            } catch (Exception e) {
            }

            driver.get("http://" + url);

            // WTF, why would their own fucking wait not work?!?
            // new WebDriverWait(driver, 5 * 1000);
        } catch (TimeoutException te) {
            handleTimeout(baseWindow, url, driver);
        } catch (org.openqa.selenium.UnhandledAlertException me) {
            log("\tModal exception caused by previous site?");

            // Retry current site.
            try {
                driver.get("http://" + url);
            } catch (TimeoutException te) {
                handleTimeout(baseWindow, url, driver);
            }
        } finally {
            ci.interrupt();
        }

        try {
            Thread.sleep(sleepTime * 1000);
        } catch (InterruptedException e) {
        }

        killPopups(baseWindow, driver);
    }

    // 4th party does not know when the crawl is over, so we send a trip signal by navigating to the "last" domain
    try {
        driver.get("http://www.josesignanini.com");
    } catch (TimeoutException te) {
    }
    try {
        Thread.sleep(60 * 1000);
    } catch (InterruptedException e) {
    }

    // copy the fourthparty database out.
    FileUtils.copyFile(new File(profileDir + "/fourthparty.sqlite"),
            new File(path + "/fourthparty-" + namedProfile + ".sqlite"));

    driver.quit();
    log("Crawling completed for " + namedProfile);

    recordLog(namedProfile);
}

From source file:com.gargoylesoftware.htmlunit.WebDriverTestCase.java

License:Apache License

/**
 * Release resources but DON'T close the browser if we are running with a real browser.
 * Note that HtmlUnitDriver is not cached by default, but that can be configured by {@link #isWebClientCached()}.
 *//*  w  w  w  .  j  a va  2  s . co m*/
@After
@Override
public void releaseResources() {
    super.releaseResources();

    if (!isWebClientCached()) {
        if (webDriver_ != null) {
            webDriver_.quit();
        }
        assertTrue("There are still JS threads running after the test", getJavaScriptThreads().isEmpty());
    }

    if (useRealBrowser()) {
        synchronized (WEB_DRIVERS_REAL_BROWSERS) {
            final WebDriver driver = WEB_DRIVERS_REAL_BROWSERS.get(getBrowserVersion());
            if (driver != null) {
                try {
                    final String currentWindow = driver.getWindowHandle();

                    final Set<String> handles = driver.getWindowHandles();
                    // close all windows except the current one
                    handles.remove(currentWindow);

                    if (handles.size() > 0) {
                        for (final String handle : handles) {
                            try {
                                driver.switchTo().window(handle);
                                driver.close();
                            } catch (final NoSuchWindowException e) {
                                LOG.error("Error switching to browser window; quit browser.", e);
                                WEB_DRIVERS_REAL_BROWSERS.remove(getBrowserVersion());
                                WEB_DRIVERS_REAL_BROWSERS_USAGE_COUNT.remove(getBrowserVersion());
                                driver.quit();
                                return;
                            }
                        }

                        // we have to force WebDriver to treat the remaining window
                        // as the one we like to work with from now on
                        // looks like a web driver issue to me (version 2.47.2)
                        driver.switchTo().window(currentWindow);
                    }

                    driver.manage().deleteAllCookies();

                    // in the remaining window, load a blank page
                    driver.get("about:blank");
                } catch (final WebDriverException e) {
                    shutDownRealBrowsers();
                }
            }
        }
    }
}

From source file:com.hotwire.test.steps.angular.AngularModelTemplate.java

License:Open Source License

@Override
public void clickCommentCardLink(String page) {
    if (page.equals("home")) {
        new AngularHomePage(getWebdriverInstance()).clickOlabLink();
    } else if (page.equals("results")) {
        new AngularHotelResultsPage(getWebdriverInstance()).clickOlabLink();
    } else if (page.equals("details")) {
        new AngularHotelDetailsPage(getWebdriverInstance()).clickOlabLink();
    } else {/* w w w.j  a v  a2  s  . c  om*/
        throw new UnimplementedTestException(page + ": not valid page id for this method.");
    }
    LOGGER.info(">>>>> Switching to comment card window <<<<<");
    // Need to switch to comment card window. Looping through set as it is not guaranteed what order will be
    // returned. Assuming there will only be 2 windows opened as anymore will be problematic.
    WebDriver webdriverInstance = getWebdriverInstance();
    String parentWindow = webdriverInstance.getWindowHandle();
    //String parentTitle = webdriverInstance.getTitle();
    for (String handle : webdriverInstance.getWindowHandles()) {
        LOGGER.info("Browser window handle: " + handle);
        if (!handle.equals(parentWindow)) {
            webdriverInstance.switchTo().window(handle);
            // Assume the window that doesn't have the parent title is the comment card.
            if (webdriverInstance.getTitle().equals("Comment card")) {
                LOGGER.info("Found comment card window.");
                break;
            }
        }
    }
}

From source file:com.hotwire.test.steps.application.ApplicationModelWebApp.java

License:Open Source License

@Override
public void submitCommentCard(String comment, int content, int design, int usability, int overall) {
    logger.info(">>>>> Switching to comment card window <<<<<");
    // Need to switch to comment card window. Looping through set as it is
    // not guaranteed what order will be
    // returned. Assuming there will only be 2 windows opened as anymore
    // will be problematic.
    WebDriver webdriverInstance = getWebdriverInstance();
    String parentWindow = webdriverInstance.getWindowHandle();
    // String parentTitle = webdriverInstance.getTitle();
    for (String handle : webdriverInstance.getWindowHandles()) {
        logger.info("Browser window handle: " + handle);
        if (!handle.equals(parentWindow)) {
            webdriverInstance.switchTo().window(handle);
            // Assume the window that doesn't have the parent title is the
            // comment card.
            if (webdriverInstance.getTitle().equals("Comment card")) {
                logger.info("Found comment card window.");
                break;
            }/* w w w . ja v a2  s .c o  m*/
        }
    }
    CommentCardPage commentCardPage = new CommentCardPage(getWebdriverInstance());
    commentCardPage.typeComment(comment);
    commentCardPage.rateContent(content);
    commentCardPage.rateDesign(design);
    commentCardPage.rateUsability(usability);
    commentCardPage.rateOverall(overall);
    commentCardPage.clickSubmitButton();

    logger.info("Comment card sent. Switching to parent browser window.");
    getWebdriverInstance().switchTo().window(getWebdriverInstance().getWindowHandles().toArray()[0].toString());
}

From source file:com.hotwire.test.steps.search.hotel.HotelSearchModelTemplate.java

License:Open Source License

@Override
public void clickCommentCardLink() {
    HotelResultsPage resultsPage = new HotelResultsPage(getWebdriverInstance());
    resultsPage.clickCommentCardLink();/*  w  w  w  .  jav a  2  s . c  o  m*/
    logger.info(">>>>> Switching to comment card window <<<<<");
    // Need to switch to comment card window. Looping through set as it is not guaranteed what order will be
    // returned. Assuming there will only be 2 windows opened as anymore will be problematic.
    WebDriver webdriverInstance = getWebdriverInstance();
    String parentWindow = webdriverInstance.getWindowHandle();
    // String parentTitle = webdriverInstance.getTitle();
    for (String handle : webdriverInstance.getWindowHandles()) {
        logger.info("Browser window handle: " + handle);
        if (!handle.equals(parentWindow)) {
            webdriverInstance.switchTo().window(handle);
            // Assume the window that doesn't have the parent title is the comment card.
            if (webdriverInstance.getTitle().equals("Comment card")) {
                logger.info("Found comment card window.");
                break;
            }
        }
    }
}