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:com.java.AppTestType_18_11_2015.java

public void EQITQUESFWDTOSELLER(WebDriver driver, String fieldText) {

    try {/*from w  w  w.j a va 2  s  . c  o m*/

        String field = fieldText;

        NAVIGATETOLISTINGDETAILSPAGE(driver);

        getvalue = driver.findElement(By.xpath("//*[@id='ONengine']/div[7]/span")).getText();

        System.out.println(getvalue);
        // SUMAN

        driver.findElement(By.xpath("//input[@type='button' and @value='Ask it Now']")).click();
        Thread.sleep(2000);
        driver.findElement(By.id("listingQuestion")).click();
        String question = "Could you forward my question to SELLER?";
        driver.findElement(By.id("listingQuestion")).sendKeys(question);
        Thread.sleep(1000);
        driver.findElement(By.name("submitq")).click();
        Thread.sleep(4000);
        driver.findElement(By.xpath("(//input[@value='OK'])[2]")).click();
        Thread.sleep(4000);

        /* driver.findElement(By.id("uname")).click();
        Thread.sleep(10000);
        driver.findElement(By.linkText("Sign Out")).click();*/
        SIGNOUT(driver);

        driver.manage().deleteAllCookies();
        driver.navigate().refresh();

        driver.get(fieldText);
        driver.manage().deleteAllCookies();
        driver.findElement(By.id("aurid")).sendKeys("mglaz@assetnation.com");

        driver.findElement(By.id("apwd")).sendKeys("Equipment1$");
        driver.findElement(By.xpath("//input[@value='Login']")).click();

        driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);

        driver.findElement(By.id("userAgreementBtn")).click();

        Thread.sleep(2000);

        System.out.println("Searching for lot id : " + getvalue);
        driver.findElement(By.name("search_string")).clear();
        driver.findElement(By.name("search_string")).sendKeys(getvalue);
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        ;
        driver.findElement(By.xpath("//button")).click();

        driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);

        driver.findElement(By.linkText("Lot Q/A")).click();
        WebDriverWait wait = new WebDriverWait(driver, 20);
        wait.until(ExpectedConditions.elementToBeClickable(By.linkText("Forward")));

        String ParentHandle = driver.getWindowHandle();
        driver.findElement(By.linkText("Forward")).click();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        ;
        for (String winHandle : driver.getWindowHandles()) {

            System.out.println("Entered For Loop");
            driver.switchTo().window(winHandle);
        }

        Thread.sleep(10000);
        driver.findElement(By.xpath("//*[contains(@onclick,'FORWARDED TO SELLER')]")).click();
        driver.findElement(By.id("id_button_forward")).click();

        driver.findElement(By.id("id_frm_textarea_reply")).sendKeys("change in question forward to seller");
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

        driver.findElement(By.id("id_button_forward_seller_location")).click();

        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        ;

        driver.switchTo().alert().accept();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        ;
        driver.switchTo().window(ParentHandle);

        resultDetails.setFlag(true);

    } catch (StaleElementReferenceException e) {

        if (retries < MAX_STALE_ELEMENT_RETRIES) {

            retries++;
        }

        else {

            throw e;
        }
    } catch (Exception e) {

        resultDetails.setFlag(false);

        resultDetails.setErrorMessage("seller is not displayed for this listing");
        e.printStackTrace();
    }

}

From source file:com.java.AppTestType_18_11_2015.java

public void FORWARDTOSTORAGE(WebDriver driver, String fieldText) {

    try {/* www .  j  a va 2 s.c o  m*/

        NAVIGATETOLISTINGDETAILSPAGE(driver);
        driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
        getvalue = driver.findElement(By.xpath("//*[@id='ONengine']/div[7]/span")).getText();

        System.out.println(getvalue);
        // SUMAN

        driver.findElement(By.xpath("//input[@type='button' and @value='Ask it Now']")).click();
        Thread.sleep(2000);
        driver.findElement(By.id("listingQuestion")).click();
        String question = "Could you forward my question to Storage Location?";
        driver.findElement(By.id("listingQuestion")).sendKeys(question);
        Thread.sleep(1000);
        driver.findElement(By.name("submitq")).click();
        Thread.sleep(4000);
        driver.findElement(By.xpath("(//input[@value='OK'])[2]")).click();
        Thread.sleep(4000);

        /* driver.findElement(By.id("uname")).click();
        Thread.sleep(10000);
        driver.findElement(By.linkText("Sign Out")).click();*/
        SIGNOUT(driver);

        driver.manage().deleteAllCookies();
        driver.navigate().refresh();

        driver.get(fieldText);
        driver.manage().deleteAllCookies();
        driver.findElement(By.id("aurid")).sendKeys("mglaz@assetnation.com");

        driver.findElement(By.id("apwd")).sendKeys("Equipment1$");
        driver.findElement(By.xpath("//input[@value='Login']")).click();

        driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);

        driver.findElement(By.id("userAgreementBtn")).click();

        Thread.sleep(2000);

        System.out.println("Searching for lot id : " + getvalue);
        driver.findElement(By.name("search_string")).clear();
        driver.findElement(By.name("search_string")).sendKeys(getvalue);
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        ;
        driver.findElement(By.xpath("//button")).click();

        driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);

        driver.findElement(By.linkText("Lot Q/A")).click();

        WebDriverWait wait = new WebDriverWait(driver, 20);
        wait.until(ExpectedConditions.elementToBeClickable(By.linkText("Forward")));

        String ParentHandle = driver.getWindowHandle();
        driver.findElement(By.linkText("Forward")).click();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        ;
        for (String winHandle : driver.getWindowHandles()) {

            System.out.println("Entered For Loop");
            driver.switchTo().window(winHandle);
        }
        Thread.sleep(5000);
        driver.findElement(By.xpath("//*[contains(@onclick,'FORWARDED TO LOCATION')]")).click();
        driver.findElement(By.id("id_button_forward")).click();

        driver.findElement(By.id("id_button_forward_seller_location")).click();

        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        ;

        driver.switchTo().alert().accept();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        ;
        driver.switchTo().window(ParentHandle);

        resultDetails.setFlag(true);

    } catch (Exception e) {

        resultDetails.setFlag(false);

        resultDetails.setErrorMessage("Storage location is not displayed for this listing");
        e.printStackTrace();
    }

}

From source file:com.java.AppTestType_18_11_2015.java

public void FORWARDTOPM(WebDriver driver, String fieldText) {

    try {//from w ww .ja  v  a2s  . co m

        NAVIGATETOLISTINGDETAILSPAGE(driver);
        driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
        getvalue = driver.findElement(By.xpath("//*[@id='ONengine']/div[7]/span")).getText();

        System.out.println(getvalue);
        // SUMAN

        driver.findElement(By.xpath("//input[@type='button' and @value='Ask it Now']")).click();
        Thread.sleep(2000);
        driver.findElement(By.id("listingQuestion")).click();
        String question = "Could you forward my question to SELLER?";
        driver.findElement(By.id("listingQuestion")).sendKeys(question);
        Thread.sleep(1000);
        driver.findElement(By.name("submitq")).click();
        Thread.sleep(4000);
        driver.findElement(By.xpath("(//input[@value='OK'])[2]")).click();
        Thread.sleep(4000);

        /* driver.findElement(By.id("uname")).click();
        Thread.sleep(10000);
        driver.findElement(By.linkText("Sign Out")).click();*/
        SIGNOUT(driver);

        driver.manage().deleteAllCookies();
        driver.navigate().refresh();

        driver.get(fieldText);
        driver.manage().deleteAllCookies();
        driver.findElement(By.id("aurid")).sendKeys("mglaz@assetnation.com");

        driver.findElement(By.id("apwd")).sendKeys("Equipment1$");
        driver.findElement(By.xpath("//input[@value='Login']")).click();

        driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);

        driver.findElement(By.id("userAgreementBtn")).click();

        Thread.sleep(2000);

        System.out.println("Searching for lot id : " + getvalue);
        driver.findElement(By.name("search_string")).clear();
        driver.findElement(By.name("search_string")).sendKeys(getvalue);
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        ;
        driver.findElement(By.xpath("//button")).click();
        driver.findElement(By.linkText("Lot Q/A")).click();
        WebDriverWait wait = new WebDriverWait(driver, 20);
        wait.until(ExpectedConditions.elementToBeClickable(By.linkText("Forward")));

        String ParentHandle = driver.getWindowHandle();
        driver.findElement(By.linkText("Forward")).click();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        ;
        for (String winHandle : driver.getWindowHandles()) {

            System.out.println("Entered For Loop");
            driver.switchTo().window(winHandle);
        }
        Thread.sleep(5000);
        driver.findElement(By.xpath("//*[contains(@onclick,'FORWARDED TO PM')]")).click();
        driver.findElement(By.id("id_button_forward")).click();

        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        ;

        driver.switchTo().alert().accept();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        ;
        driver.switchTo().window(ParentHandle);

        resultDetails.setFlag(true);

    } catch (StaleElementReferenceException e) {

        if (retries < MAX_STALE_ELEMENT_RETRIES) {

            retries++;
        }

        else {

            throw e;
        }
    } catch (Exception e) {

        resultDetails.setFlag(false);
        resultDetails.setErrorMessage("PM is not displayed for this listing");
        e.printStackTrace();
    }

}

From source file:com.java.AppTestType_18_11_2015.java

public void ASKQUESTION(WebDriver driver, String fieldText, String value) {

    try {//w  ww. j a v a2 s.  c o m
        int i;
        List<WebElement> listings = driver.findElements(By.cssSelector("a[href*='/listing?listingid']"));

        for (i = 0; i < listings.size(); i++) {

            WebElement requiredlisting = listings.get(i);
            requiredlisting.click();

            getvalue = driver.findElement(By.xpath("//div[7]/span")).getText();
            System.out.println(getvalue);

            driver.findElement(By.xpath("//div[3]/div[2]/input")).click();
            driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
            ;

            driver.findElement(By.id("listingQuestion")).click();
            driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
            ;
            driver.findElement(By.id("listingQuestion")).sendKeys("where is the listing located");
            driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
            ;
            driver.findElement(By.name("submitq")).click();
            driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
            ;

            driver.findElement(By.xpath("//div/div[2]/div[3]/input")).click();
            driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
            ;

            driver.findElement(By.cssSelector("span")).click();

            driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
            ;
            driver.findElement(By.linkText("Sign Out")).click();
            driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
            ;
            driver.manage().deleteAllCookies();
            driver.navigate().refresh();
            driver.get(fieldText);
            driver.manage().deleteAllCookies();
            driver.findElement(By.id("aurid")).sendKeys("mglaz@assetnation.com");

            driver.findElement(By.id("apwd")).sendKeys("Equipment1$");
            driver.findElement(By.xpath("//input[@value='Login']")).click();

            driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);

            driver.findElement(By.id("userAgreementBtn")).click();

            driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

            System.out.println(getvalue);
            driver.findElement(By.id("quicksearch")).sendKeys(getvalue);
            driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
            ;
            driver.findElement(By.cssSelector("input.quicksearch_go")).click();

            driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

            driver.findElement(By.linkText("Lot Q/A")).click();

            driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
            ;

            String ParentHandle = driver.getWindowHandle();
            driver.findElement(By.linkText("Forward")).click();
            driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
            ;
            for (String winHandle : driver.getWindowHandles()) {

                System.out.println("Entered For Loop");
                driver.switchTo().window(winHandle);
            }

            driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
            ;
            driver.findElement(By.xpath("//td/input[4]")).click();
            driver.findElement(By.id("id_button_forward")).click();

            driver.findElement(By.id("id_button_forward_seller_location")).click();

            driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
            ;

            driver.switchTo().alert().accept();
            driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
            ;
            driver.switchTo().window(ParentHandle);
            driver.findElement(By.xpath("//ul/ul/li/a")).click();

            driver.findElement(By.xpath("//td[2]/a")).click();
            String seller = driver.findElement(By.id("id_frm_Email_Address")).getAttribute("value");

            driver.findElement(By.linkText("Logout")).click();
            driver.manage().deleteAllCookies();
            driver.navigate().refresh();
            driver.get(value);
            driver.findElement(By.id("sign")).click();

            driver.findElement(By.id("loginfield")).sendKeys(seller);
            driver.findElement(By.id("pwdfield")).sendKeys("Equipment1$");
            driver.findElement(By.cssSelector("input.secondary_110")).click();
            driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
            ;
            driver.findElement(By.linkText("MYONE")).click();
            driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

            resultDetails.setFlag(true);

        }

    } catch (Exception e) {

        resultDetails.setFlag(false);
    }

}

From source file:com.java.AppTestType_18_11_2015.java

public void APPROVEUSER(WebDriver driver, String fieldText, String value) {
    //To Handle Approve User Popup 
    //FieldText---The User's FullName   and Value-----OK or Cancel
    try {// w ww  .  j  a  va  2 s  .  c o  m
        driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
        driver.findElement(By.linkText(fieldText)).click();
        Thread.sleep(2000);
        String parentwindow = driver.getWindowHandle();
        if (value.equalsIgnoreCase("OK")) {
            driver.findElement(By.linkText("Approve User")).click();
            Thread.sleep(2000);

            driver.switchTo().alert().accept();

            for (String win : driver.getWindowHandles()) {
                driver.switchTo().window(win);
                try {
                    driver.switchTo().alert().accept();
                } catch (NoAlertPresentException e) {
                    Robot robot = new Robot();
                    robot.keyPress(KeyEvent.VK_SPACE);
                    Thread.sleep(3000);
                }

            }
            Thread.sleep(20000);
            driver.switchTo().window(parentwindow);
            WebDriverWait wait = new WebDriverWait(driver, 20);
            wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("id_frm_Email_Address")));
            String Email = driver.findElement(By.id("id_frm_Email_Address")).getText();
            driver.findElement(By.name("email")).sendKeys(EMAIL);
            driver.findElement(By.xpath("//input[@value='Search']")).click();

            String Type = driver.findElement(By.xpath("//input[@value='Search']/following::tr[3]/td[6]"))
                    .getText();
            String Active_Status = driver
                    .findElement(By.xpath("//input[@value='Search']/following::tr[3]/td[6]")).getText();
            String BStatus = driver.findElement(By.xpath("//input[@value='Search']/following::tr[3]/td[6]"))
                    .getText();
            String SStatus = driver.findElement(By.xpath("//input[@value='Search']/following::tr[3]/td[6]"))
                    .getText();

            if (Type.equalsIgnoreCase("L") && Active_Status.equalsIgnoreCase("Active")
                    && BStatus.equalsIgnoreCase("Approved") && SStatus.equalsIgnoreCase("Approved")) {
                resultDetails.setFlag(true);
            }
        } else if (value.equalsIgnoreCase("CANCEL")) {
            driver.findElement(By.linkText("Approve User")).click();
            Thread.sleep(2000);
            //Robot robot = new Robot();
            // Simulate SPACE KEY press to click on OK button
            //robot.keyPress(KeyEvent.VK_ESCAPE);
            driver.switchTo().alert().dismiss();
            resultDetails.setFlag(true);

        }

    }

    catch (Exception e) {

        e.printStackTrace();
        resultDetails.setFlag(false);
    }
}

From source file:com.liferay.cucumber.selenium.BaseWebDriverImpl.java

License:Open Source License

public BaseWebDriverImpl(String browserURL, WebDriver webDriver) {
    _webDriver = webDriver;//  w  w  w  .jav  a2  s  .  c  o  m

    initKeysSpecialChars();

    WebDriverHelper.setDefaultWindowHandle(webDriver.getWindowHandle());
    WebDriverHelper.setNavigationBarHeight(120);

    System.setProperty("java.awt.headless", "false");

    String outputDirName = _OUTPUT_DIR_NAME;
    String sikuliImagesDirName = _TEST_DEPENDENCIES_DIR_NAME + "//sikuli//linux//";
    String testDependenciesDirName = _TEST_DEPENDENCIES_DIR_NAME;

    if (OSDetector.isApple()) {
        sikuliImagesDirName = StringUtil.replace(sikuliImagesDirName, "linux", "osx");
    } else if (OSDetector.isWindows()) {
        outputDirName = StringUtil.replace(outputDirName, "//", "\\");

        sikuliImagesDirName = StringUtil.replace(sikuliImagesDirName, "//", "\\");
        sikuliImagesDirName = StringUtil.replace(sikuliImagesDirName, "linux", "windows");

        testDependenciesDirName = StringUtil.replace(testDependenciesDirName, "//", "\\");
    }

    _outputDirName = outputDirName;
    _sikuliImagesDirName = sikuliImagesDirName;
    _testDependenciesDirName = testDependenciesDirName;

    WebDriver.Options options = webDriver.manage();

    WebDriver.Window window = options.window();

    window.setSize(new Dimension(1300, 768));

    webDriver.get(browserURL);
}

From source file:com.liferay.faces.test.selenium.browser.internal.BrowserDriverImpl.java

License:Open Source License

@Override
public String getCurrentWindowId() {

    WebDriver webDriver = getWebDriver();

    return webDriver.getWindowHandle();
}

From source file:com.maoyan.pf.webcollector.spider.ShowrateCrawler.java

License:Open Source License

public static void main(String[] args) throws Exception {
    Executor executor = new Executor() {
        @Override//w ww .j a  va 2  s . c  o 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("show_rate")) {
                    db.getCollection(s).drop();
                }
            }
            DBCollection dbCollection = db.getCollection("show_rate");
            //                ProfilesIni pi = new ProfilesIni();
            //                FirefoxProfile profile = pi.getProfile("default");
            WebDriver driver = new FirefoxDriver();
            driver.manage().window().maximize();
            driver.manage().timeouts().pageLoadTimeout(3, TimeUnit.SECONDS);
            //                driver.setJavascriptEnabled(false);
            System.out.println("??\n");
            driver.get(datum.getUrl());
            //                System.out.println(driver.getPageSource());
            List<WebElement> movie_name = driver
                    .findElements(By.xpath("//div[@id='playPlan_table']/ul/li[@class='c1 lineDot']"));
            List<WebElement> boxoffice_rate = driver
                    .findElements(By.xpath("//div[@id='playPlan_table']/ul/li[@class='c2 red']"));
            List<WebElement> visit_pershow = driver
                    .findElements(By.xpath("//div[@id='playPlan_table']/ul/li[@class='c3 gray']"));
            WebElement title = driver.findElement(By.xpath("//p[@id='pieTip']"));
            for (int i = 0; i < movie_name.size(); i++) {
                String movie_name_val = movie_name.get(i).getText();
                String boxofficerate_val = boxoffice_rate.get(i).getText();
                String visit_pershow_val = visit_pershow.get(i).getText();
                BasicDBObject dbObject = new BasicDBObject();
                dbObject.append("title", title.getText()).append("is_gold", "?")
                        .append("show_type", "?").append("movie_name", movie_name_val)
                        .append("boxoffice_rate", boxofficerate_val).append("visit_pershow", visit_pershow_val);
                dbCollection.insert(dbObject);
            }
            System.out.println("?\n");
            WebElement click_gold = driver.findElement(By.id("playPlan_time"));
            click_gold.click();
            String gold_seat = driver.getWindowHandle();
            driver.switchTo().window(gold_seat);
            List<WebElement> movie_name_gold = driver
                    .findElements(By.xpath("//div[@id='playPlan_table']/ul/li[@class='c1 lineDot']"));
            List<WebElement> boxoffice_rate_gold = driver
                    .findElements(By.xpath("//div[@id='playPlan_table']/ul/li[@class='c2 red']"));
            List<WebElement> visit_pershow_gold = driver
                    .findElements(By.xpath("//div[@id='playPlan_table']/ul/li[@class='c3 gray']"));
            WebElement title_gold = driver.findElement(By.xpath("//p[@id='pieTip']"));
            for (int i = 0; i < movie_name_gold.size(); i++) {
                String movie_name_val = movie_name_gold.get(i).getText();
                String boxofficerate_val = boxoffice_rate_gold.get(i).getText();
                String visit_pershow_val = visit_pershow_gold.get(i).getText();
                BasicDBObject dbObject = new BasicDBObject();
                dbObject.append("title", title_gold.getText()).append("is_gold", "")
                        .append("show_type", "?").append("movie_name", movie_name_val)
                        .append("boxoffice_rate", boxofficerate_val).append("visit_pershow", visit_pershow_val);
                dbCollection.insert(dbObject);
            }
            System.out.println("?\n");
            WebElement click_vist = driver.findElement(By.xpath("//*[@id='show--type']"));
            click_vist.click();
            String gold_vist = driver.getWindowHandle();
            driver.switchTo().window(gold_vist);
            List<WebElement> movie_name_gold_visit = driver
                    .findElements(By.xpath("//div[@id='playPlan_table']/ul/li[@class='c1 lineDot']"));
            List<WebElement> boxoffice_rate_gold_visit = driver
                    .findElements(By.xpath("//div[@id='playPlan_table']/ul/li[@class='c2 red']"));
            List<WebElement> visit_pershow_gold_visit = driver
                    .findElements(By.xpath("//div[@id='playPlan_table']/ul/li[@class='c3 gray']"));
            WebElement title_gold_visit = driver.findElement(By.xpath("//p[@id='pieTip']"));
            for (int i = 0; i < movie_name_gold_visit.size(); i++) {
                String movie_name_val = movie_name_gold_visit.get(i).getText();
                String boxofficerate_val = boxoffice_rate_gold_visit.get(i).getText();
                String visit_pershow_val = visit_pershow_gold_visit.get(i).getText();
                BasicDBObject dbObject = new BasicDBObject();
                dbObject.append("title", title_gold_visit.getText()).append("is_gold", "")
                        .append("show_type", "").append("movie_name", movie_name_val)
                        .append("boxoffice_rate", boxofficerate_val).append("visit_pershow", visit_pershow_val);
                dbCollection.insert(dbObject);
            }
            System.out.println("?\n");
            click_gold.click();
            String normal_seat = driver.getWindowHandle();
            driver.switchTo().window(normal_seat);
            List<WebElement> movie_name_normal_seat = driver
                    .findElements(By.xpath("//div[@id='playPlan_table']/ul/li[@class='c1 lineDot']"));
            List<WebElement> boxoffice_rate_normal_seat = driver
                    .findElements(By.xpath("//div[@id='playPlan_table']/ul/li[@class='c2 red']"));
            List<WebElement> visit_pershow_normal_seat = driver
                    .findElements(By.xpath("//div[@id='playPlan_table']/ul/li[@class='c3 gray']"));
            WebElement title_normal_seat = driver.findElement(By.xpath("//p[@id='pieTip']"));
            for (int i = 0; i < movie_name_normal_seat.size(); i++) {
                String movie_name_val = movie_name_normal_seat.get(i).getText();
                String boxofficerate_val = boxoffice_rate_normal_seat.get(i).getText();
                String visit_pershow_val = visit_pershow_normal_seat.get(i).getText();
                BasicDBObject dbObject = new BasicDBObject();
                dbObject.append("title", title_normal_seat.getText()).append("is_gold", "?")
                        .append("show_type", "").append("movie_name", movie_name_val)
                        .append("boxoffice_rate", boxofficerate_val).append("visit_pershow", visit_pershow_val);
                dbCollection.insert(dbObject);
            }

            driver.close();
            driver.quit();
            mongoClient.close();
        }
    };

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

From source file:com.mgmtp.jfunk.web.JFunkWebDriverEventListener.java

License:Apache License

/**
 * Saves the currently displayed browser window. The page title is used for the filename -
 * preceded by some identifying information (thread, counter). Pages of the same type are
 * collected inside the same subdirectory. The subdirectory uses
 * {@link SaveOutput#getIdentifier()} for its name. If an alert is present, saving is not
 * supported and thus skipped.//  ww  w  .  jav a 2 s  .  c  o  m
 *
 * @param action
 *            the event which triggered to save the page. Will be included in the filename.
 * @param triggeredBy
 *            the object which triggered the event (e.g. a button or a link)
 */
protected void savePage(final WebDriver driver, final String action, final String triggeredBy) {
    try {
        // this updates the driver's window handles, so a subsequent call to
        // getWindowHandle() fails if the window no longer exists
        driver.getWindowHandles();
        driver.getWindowHandle();
    } catch (NoSuchWindowException ex) {
        // Window is already closed. Saving the page could cause problems, e. g.
        // ChromeDriver ould hang.
        return;
    }
    File moduleArchiveDir = moduleArchiveDirProvider.get();
    if (moduleArchiveDir == null) {
        return;
    }

    if (config.getBoolean(JFunkConstants.ARCHIVE_DO_NOT_SAVE_WHEN_ALERT, false)) {
        try {
            // Saving the page does not work if an alert is present
            driver.switchTo().alert();
            log.trace("Cannot save page. Alert is present.");
            return;
        } catch (NoAlertPresentException ex) {
            // ignore
        } catch (UnsupportedOperationException ex) {
            // ignore
            // HtmlUnit does not support alerts
        } catch (Exception ex) {
            // ignore
        }
    }

    for (SaveOutput saveOutput : SaveOutput.values()) {
        boolean saveSwitch = saveOutputMap.get(saveOutput);
        if (!saveSwitch) {
            // Saving is disabled by property
            continue;
        }

        File f = null;
        try {
            f = dumpFileCreatorProvider.get().createDumpFile(
                    new File(moduleArchiveDir, saveOutput.getIdentifier()), saveOutput.getExtension(),
                    driver.getCurrentUrl(), action);

            if (f == null) {
                return;
            }

            switch (saveOutput) {
            case HTML:
                StringBuilder html = new StringBuilder();
                html.append("<!-- Requested URL: ");
                html.append(driver.getCurrentUrl());
                html.append(" -->");
                html.append(IOUtils.LINE_SEPARATOR);
                html.append(driver.getPageSource());
                writeStringToFile(f, html.toString(), "UTF-8");
                copyFile(f, new File(moduleArchiveDir, JFunkConstants.LASTPAGE_HTML));
                log.trace("Saving page: filename={}, action={}, trigger={}, response={}", f.getName(), action,
                        triggeredBy, driver.getCurrentUrl());
                break;
            case PNG:
                if (driver instanceof TakesScreenshot) {
                    File tmpFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
                    if (tmpFile != null) {
                        copyFile(tmpFile, f);
                        log.trace("Saving page: filename={}, action={}, trigger={}, response={}", f.getName(),
                                action, triggeredBy, driver.getCurrentUrl());
                        deleteQuietly(tmpFile);
                    }
                }
                break;
            case HTML_VALIDATION:
                /*
                 * JFunkWebDriver.getPageSource() doesn't return the complete page source
                 * e.g. DOCTYPE is missing. Therefore we are using a more complicated way to
                 * retrieve the "real" page source. However, this only works when using
                 * HtmlUnitDriver.
                 */
                if (WebDriverUtils.isHtmlUnitDriver(driver)) {
                    String content = ((HtmlPage) WebDriverUtils.getHtmlUnitDriverWebClient(driver)
                            .getCurrentWindow().getEnclosedPage()).getWebResponse().getContentAsString();
                    writeStringToFile(f, content, "UTF-8");
                    HtmlValidatorUtil.validateHtml(f.getParentFile(), config, f);
                }
                break;
            default:
                throw new IllegalStateException("unknown enum constant");
            }
        } catch (Exception ex) {
            log.error("Could not save file: {}. {}", f, ex.getMessage());
            return;
        }
    }
}

From source file:com.pentaho.ctools.utils.ElementHelper.java

License:Apache License

/**
 * This method shall select a new window that has opened and return the handle for the parent window.
 * /*from w  w  w. j  av a 2  s.  c om*/
 * The handle should be stored in a string so we can go back to the parent window afterwards
 * using the SelectParentWindow method
 * 
 * @param driver
 * @return parentWindow
 */
public String SelectNewWindow(final WebDriver driver) {
    String parentWindowHandle = driver.getWindowHandle();
    Set<String> listWindows = driver.getWindowHandles();
    WaitForNewWindow(driver);
    listWindows = driver.getWindowHandles();
    // Get the windowHandler of the new open window
    Iterator<String> iterWindows = listWindows.iterator();
    while (iterWindows.hasNext()) {
        String windowHandle = iterWindows.next();
        if (windowHandle.equals(parentWindowHandle) == false) {
            driver.switchTo().window(windowHandle);
            break;
        }
    }
    return parentWindowHandle;
}