List of usage examples for org.openqa.selenium WebDriver switchTo
TargetLocator switchTo();
From source file:com.liferay.faces.test.selenium.browser.internal.BrowserDriverImpl.java
License:Open Source License
@Override public void switchToFrame(String iframeXpath) { WebElement webElement = findElementByXpath(iframeXpath); WebDriver webDriver = getWebDriver(); webDriver.switchTo().frame(webElement); }
From source file:com.liferay.faces.test.selenium.browser.internal.BrowserDriverImpl.java
License:Open Source License
@Override public void switchToWindow(String windowId) { WebDriver webDriver = getWebDriver(); webDriver.switchTo().window(windowId); }
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// www . java2 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./*from w ww . j a v 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.novartis.opensource.yada.test.YADAAdminTest.java
License:Apache License
/** * Convenience method to wrap try/catch and {@link Thread#sleep(long)} * @param d the active {@link WebDriver} * @param sleep the duration for which the {@link Thread} should sleep before continuing * @throws InterruptedException if any thread has interrupted the current thread *//*from w w w .j av a 2s.c o m*/ private void switchToActiveElement(WebDriver d, int sleep) throws InterruptedException { try { d.switchTo().activeElement(); } catch (UnsupportedCommandException e) { // Chrome driver requires above step, but Firefox driver doesn't currently support it. // This test succeeds now with the try block } Thread.sleep(sleep); }
From source file:com.pentaho.ctools.cdf.PrptComponent.java
License:Apache License
/** * ############################### Test Case 0 ############################### * * Test Case Name://from www. j a v a2s. c o m * Open Sample Page */ @Test public void tc0_OpenSamplePage_Display() { this.log.info("tc0_OpenSamplePage_Display"); // The URL for the PrptComponent under CDF samples // This sample is in: Public/plugin-samples/CDF/Documentation/Component Reference/Core Components/PrptComponent driver.get(PageUrl.PRPT_COMPONENT); // NOTE - we have to wait for loading disappear this.elemHelper.WaitForElementInvisibility(driver, By.cssSelector("div.blockUI.blockOverlay")); //Check if the some elements are already displayed //Check if element with "Line" is visible this.elemHelper.WaitForElementPresence(driver, By.cssSelector("div#sampleObject iframe")); WebDriver frameSamplePrpt = driver.switchTo().frame("sampleObject_prptFrame"); WebElement elemLine = this.elemHelper.WaitForElementPresenceAndVisible(frameSamplePrpt, By.cssSelector("div.parameter-label"), 45); assertNotNull(elemLine); this.elemHelper.WaitForElementPresence(driver, By.cssSelector("iframe#reportContent")); //Check if element with "LINE: Classic Cars" is visible WebDriver frameReportContent = frameSamplePrpt.switchTo().frame("reportContent"); WebElement elemLineClassic = this.elemHelper.WaitForElementPresenceAndVisible(frameReportContent, By.xpath("//tr/td"), 45); assertNotNull(elemLineClassic); //Back to root driver.switchTo().defaultContent(); }
From source file:com.pentaho.ctools.cdf.PrptComponent.java
License:Apache License
/** * ############################### Test Case 2 ############################### * * Test Case Name:/*from w w w.j av a 2 s. com*/ * Reload Sample * Description: * Reload the sample (not refresh page). * Steps: * 1. Click in Code and then click in button 'Try me'. */ @Test public void tc2_ReloadSample_SampleReadyToUse() { this.log.info("tc2_ReloadSample_SampleReadyToUse"); // ## Step 1 // Render again the sample this.elemHelper.ClickJS(driver, By.xpath("//div[@id='example']/ul/li[2]/a")); this.elemHelper.ClickJS(driver, By.xpath("//div[@id='code']/button")); // NOTE - we have to wait for loading disappear this.elemHelper.WaitForElementInvisibility(driver, By.cssSelector("div.blockUI.blockOverlay")); //Check if the some elements are already displayed //Check if element with "Line" is visible this.elemHelper.WaitForElementPresence(driver, By.cssSelector("div#sampleObject iframe")); WebDriver frameSamplePrpt = driver.switchTo().frame("sampleObject_prptFrame"); WebElement elemLine = this.elemHelper.WaitForElementPresenceAndVisible(frameSamplePrpt, By.cssSelector("div.parameter-label"), 45); assertNotNull(elemLine); //Check if element with "LINE: Classic Cars" is visible this.elemHelper.WaitForElementPresence(driver, By.cssSelector("iframe#reportContent")); WebDriver frameReportContent = frameSamplePrpt.switchTo().frame("reportContent"); WebElement elemLineClassic = this.elemHelper.WaitForElementPresenceAndVisible(frameReportContent, By.xpath("//tr/td"), 45); assertNotNull(elemLineClassic); //Back to root driver.switchTo().defaultContent(); // Now sample element must be displayed assertTrue(this.elemHelper.FindElement(driver, By.id("sample")).isDisplayed()); //Check the number of divs with id 'SampleObject' //Hence, we guarantee when click Try Me the previous div is replaced int nSampleObject = driver.findElements(By.id("sampleObject")).size(); assertEquals(1, nSampleObject); }
From source file:com.pentaho.ctools.cdf.require.PrptComponent.java
License:Apache License
/** * ############################### Test Case 1 ############################### * * Test Case Name:/*w w w. j a va 2 s .c o m*/ * Display Content * Description: * Check if the contents present in page is the expected. * Steps: * 1. Check title web page and sample title. */ @Test public void tc0_OpenSamplePage_Display() { this.log.info("tc0_OpenSamplePage_Display"); // The URL for the PrptComponent under CDF samples // This sample is in: Public/plugin-samples/CDF/Require Samples/Documentation/Component Reference/Core Components/PrptComponent driver.get(PageUrl.PRPT_COMPONENT_REQUIRE); // NOTE - we have to wait for loading disappear this.elemHelper.WaitForElementPresence(driver, By.cssSelector("div.blockUI.blockOverlay"), 10); this.elemHelper.WaitForElementInvisibility(driver, By.cssSelector("div.blockUI.blockOverlay")); //Check if the some elements are already displayed //Check if element with "Line" is visible this.elemHelper.WaitForElementPresence(driver, By.cssSelector("div#sampleObject iframe")); WebDriver frameSamplePrpt = driver.switchTo().frame("sampleObject_prptFrame"); WebElement elemLine = this.elemHelper.WaitForElementPresenceAndVisible(frameSamplePrpt, By.cssSelector("div.parameter-label"), 45); assertNotNull(elemLine); //Check if element with "LINE: Classic Cars" is visible this.elemHelper.WaitForElementPresence(driver, By.cssSelector("iframe#reportContent")); WebDriver frameReportContent = frameSamplePrpt.switchTo().frame("reportContent"); WebElement elemLineClassic = this.elemHelper.WaitForElementPresenceAndVisible(frameReportContent, By.xpath("//tr/td"), 45); assertNotNull(elemLineClassic); //Back to root driver.switchTo().defaultContent(); }
From source file:com.pentaho.ctools.cdf.require.PrptComponent.java
License:Apache License
/** * ############################### Test Case 2 ############################### * * Test Case Name://from w w w.ja va 2 s . c o m * Reload Sample * Description: * Reload the sample (not refresh page). * Steps: * 1. Click in Code and then click in button 'Try me'. */ @Test public void tc2_ReloadSample_SampleReadyToUse() { this.log.info("tc2_ReloadSample_SampleReadyToUse"); /* * ## Step 1 */ // Render again the sample this.elemHelper.ClickJS(driver, By.xpath("//div[@id='example']/ul/li[2]/a")); this.elemHelper.ClickJS(driver, By.xpath("//div[@id='code']/button")); // NOTE - we have to wait for loading disappear this.elemHelper.WaitForElementPresence(driver, By.cssSelector("div.blockUI.blockOverlay"), 10); this.elemHelper.WaitForElementInvisibility(driver, By.cssSelector("div.blockUI.blockOverlay")); //Check if the some elements are already displayed //Check if element with "Line" is visible this.elemHelper.WaitForElementPresence(driver, By.cssSelector("div#sampleObject iframe")); WebDriver frameSamplePrpt = driver.switchTo().frame("sampleObject_prptFrame"); WebElement elemLine = this.elemHelper.WaitForElementPresenceAndVisible(frameSamplePrpt, By.cssSelector("div.parameter-label"), 45); assertNotNull(elemLine); //Check if element with "LINE: Classic Cars" is visible this.elemHelper.WaitForElementPresence(driver, By.cssSelector("iframe#reportContent")); WebDriver frameReportContent = frameSamplePrpt.switchTo().frame("reportContent"); WebElement elemLineClassic = this.elemHelper.WaitForElementPresenceAndVisible(frameReportContent, By.xpath("//tr/td"), 45); assertNotNull(elemLineClassic); //Back to root driver.switchTo().defaultContent(); // Now sample element must be displayed assertTrue(this.elemHelper.FindElement(driver, By.id("sample")).isDisplayed()); //Check the number of divs with id 'SampleObject' //Hence, we guarantee when click Try Me the previous div is replaced int nSampleObject = driver.findElements(By.id("sampleObject")).size(); assertEquals(1, nSampleObject); }
From source file:com.pentaho.ctools.utils.ElementHelper.java
License:Apache License
/** * This function shall wait for the alert window to be closed or doesn't * exist.//from www . j av a 2 s.co m * * @param driver */ public void WaitForAlertNotPresent(WebDriver driver) { this.log.debug("WaitForAlertNotPresent::Enter"); Wait<WebDriver> wait = new FluentWait<WebDriver>(driver).withTimeout(30, TimeUnit.SECONDS).pollingEvery(100, TimeUnit.MILLISECONDS); wait.until(new ExpectedCondition<Boolean>() { @Override public Boolean apply(WebDriver d) { Boolean alertExist = false; try { d.switchTo().alert(); alertExist = true; } catch (NoAlertPresentException e) { // Ignore the exception } return alertExist != true; } }); this.log.debug("WaitForAlertNotPresent::Exit"); }