Search in sources :

Example 1 with WebWindow

use of com.gargoylesoftware.htmlunit.WebWindow in project JSCover by tntim96.

the class HtmlUnitServerTest method shouldStoreResultViaJavaScriptCall.

@Test
public void shouldStoreResultViaJavaScriptCall() throws Exception {
    File jsonFile = new File(getReportDir() + "/directory/jscoverage.json");
    if (jsonFile.exists())
        jsonFile.delete();
    HtmlPage page = webClient.getPage("http://localhost:9001/jscoverage.html");
    ((HtmlInput) page.getHtmlElementById("location")).setValueAttribute("http://localhost:9001/example/index.html");
    page.getHtmlElementById("openInWindowButton").click();
    webClient.waitForBackgroundJavaScript(100);
    verifyTotal(webClient, page, 15);
    WebWindow webWindow = webClient.getWebWindowByName("jscoverage_window");
    ((HtmlPage) webWindow.getEnclosedPage()).executeJavaScript("jscoverage_report('directory');");
    webClient.waitForBackgroundJavaScript(2000);
    String json = ioUtils.toString(jsonFile);
    assertThat(json, containsString("/script.js"));
    page = webClient.getPage("file:///" + new File(getReportDir() + "/directory/jscoverage.html").getAbsolutePath());
    verifyTotal(webClient, page, 15);
}
Also used : HtmlPage(com.gargoylesoftware.htmlunit.html.HtmlPage) Matchers.containsString(org.hamcrest.Matchers.containsString) File(java.io.File) HtmlInput(com.gargoylesoftware.htmlunit.html.HtmlInput) WebWindow(com.gargoylesoftware.htmlunit.WebWindow) Test(org.junit.Test)

Example 2 with WebWindow

use of com.gargoylesoftware.htmlunit.WebWindow in project JSCover by tntim96.

the class HtmlUnitServerTest method testWorkInInvertedMode.

protected void testWorkInInvertedMode(int branchPercentage1, int branchPercentage2, int functionPercentage1, int functionPercentage2) throws IOException {
    HtmlPage page = webClient.getPage("http://localhost:9001/example/index.html");
    page.getHtmlElementById("launchJSCover").click();
    webClient.waitForBackgroundJavaScript(100);
    WebWindow webWindow = webClient.getWebWindowByName("JSCoverInvertedMode");
    HtmlPage jsCoverPage = (HtmlPage) webWindow.getEnclosedPage();
    verifyTotal(webClient, jsCoverPage, 15, branchPercentage1, functionPercentage1);
    page.getHtmlElementById("radio3").click();
    webClient.waitForBackgroundJavaScript(100);
    jsCoverPage.executeJavaScript("jscoverage_recalculateSummaryTab();");
    webClient.waitForBackgroundJavaScript(500);
    verifyTotal(webClient, jsCoverPage, 73, branchPercentage2, functionPercentage2);
}
Also used : HtmlPage(com.gargoylesoftware.htmlunit.html.HtmlPage) WebWindow(com.gargoylesoftware.htmlunit.WebWindow)

Example 3 with WebWindow

use of com.gargoylesoftware.htmlunit.WebWindow in project zeppelin by apache.

the class ScreenCaptureHtmlUnitDriver method downloadCssAndImages.

// http://stackoverflow.com/questions/2244272/how-can-i-tell-htmlunits-webclient-to-download-images-and-css
protected byte[] downloadCssAndImages(WebClient webClient, HtmlPage page) throws Exception {
    WebWindow currentWindow = webClient.getCurrentWindow();
    Map<String, String> urlMapping = new HashMap<>();
    Map<String, byte[]> files = new HashMap<>();
    WebWindow window = null;
    try {
        window = webClient.getWebWindowByName(page.getUrl().toString() + "_screenshot");
        webClient.getPage(window, new WebRequest(page.getUrl()));
    } catch (Exception e) {
        LOGGER.error("Exception in ScreenCaptureHtmlUnitDriver while downloadCssAndImages ", e);
        window = webClient.openWindow(page.getUrl(), page.getUrl().toString() + "_screenshot");
    }
    String xPathExpression = "//*[name() = 'img' or name() = 'link' and (@type = 'text/css' or @type = 'image/x-icon') or  @type = 'text/javascript']";
    List<?> resultList = page.getByXPath(xPathExpression);
    Iterator<?> i = resultList.iterator();
    while (i.hasNext()) {
        try {
            HtmlElement el = (HtmlElement) i.next();
            String resourceSourcePath = el.getAttribute("src").equals("") ? el.getAttribute("href") : el.getAttribute("src");
            if (resourceSourcePath == null || resourceSourcePath.equals(""))
                continue;
            URL resourceRemoteLink = page.getFullyQualifiedUrl(resourceSourcePath);
            String resourceLocalPath = mapLocalUrl(page, resourceRemoteLink, resourceSourcePath, urlMapping);
            urlMapping.put(resourceSourcePath, resourceLocalPath);
            if (!resourceRemoteLink.toString().endsWith(".css")) {
                byte[] image = downloadImage(webClient, window, resourceRemoteLink);
                files.put(resourceLocalPath, image);
            } else {
                String css = downloadCss(webClient, window, resourceRemoteLink);
                for (String cssImagePath : getLinksFromCss(css)) {
                    URL cssImagelink = page.getFullyQualifiedUrl(cssImagePath.replace("\"", "").replace("\'", "").replace(" ", ""));
                    String cssImageLocalPath = mapLocalUrl(page, cssImagelink, cssImagePath, urlMapping);
                    files.put(cssImageLocalPath, downloadImage(webClient, window, cssImagelink));
                }
                files.put(resourceLocalPath, replaceRemoteUrlsWithLocal(css, urlMapping).replace("resources/", "./").getBytes());
            }
        } catch (Exception e) {
            LOGGER.error("Exception in ScreenCaptureHtmlUnitDriver while resultList.iterator ", e);
        }
    }
    String pagesrc = replaceRemoteUrlsWithLocal(page.getWebResponse().getContentAsString(), urlMapping);
    files.put("page.html", pagesrc.getBytes());
    webClient.setCurrentWindow(currentWindow);
    return createZip(files);
}
Also used : WebRequest(com.gargoylesoftware.htmlunit.WebRequest) HashMap(java.util.HashMap) HtmlElement(com.gargoylesoftware.htmlunit.html.HtmlElement) WebDriverException(org.openqa.selenium.WebDriverException) IOException(java.io.IOException) URL(java.net.URL) WebWindow(com.gargoylesoftware.htmlunit.WebWindow)

Example 4 with WebWindow

use of com.gargoylesoftware.htmlunit.WebWindow in project yyl_example by Relucent.

the class HtmlUnitTest3 method main.

public static void main(String[] args) throws Exception {
    WebClient webClient = new WebClient(BrowserVersion.FIREFOX_68);
    try {
        webClient.setCssErrorHandler(new SilentCssErrorHandler());
        webClient.setAjaxController(new NicelyResynchronizingAjaxController());
        webClient.getOptions().setCssEnabled(true);
        webClient.getOptions().setRedirectEnabled(false);
        webClient.getOptions().setAppletEnabled(false);
        webClient.getOptions().setJavaScriptEnabled(true);
        webClient.getOptions().setPopupBlockerEnabled(true);
        webClient.getOptions().setTimeout(10000);
        // JS运行错误时,是否抛出异常
        webClient.getOptions().setThrowExceptionOnScriptError(false);
        // webClient.waitForBackgroundJavaScript(10 * 1000);
        HtmlPage page = webClient.getPage("https://www.baidu.com/");
        WebWindow webWindow = page.getEnclosingWindow();
        System.out.println("# 等待页面加载");
        waitFor(() -> {
            DomElement input = page.getElementById("kw");
            return input instanceof HtmlInput;
        });
        System.out.println("# 文本框输入 htmlunit ");
        HtmlInput kw = (HtmlInput) page.getElementById("kw");
        kw.setAttribute("value", "htmlunit");
        System.out.println("# 触发回车事件");
        Thread.sleep(1000);
        // Enter
        kw.type(13);
        System.out.println("# 等待页面跳转");
        Thread.sleep(1000);
        HtmlPage page2 = (HtmlPage) webWindow.getEnclosedPage();
        System.out.println(page2.getUrl());
        DomNodeList<DomNode> nodes = page2.querySelectorAll(".result.c-container h3 a");
        System.out.println("# 输出结果");
        for (DomNode node : nodes) {
            System.out.println(node.asText());
        }
    } finally {
        webClient.close();
    }
}
Also used : DomNode(com.gargoylesoftware.htmlunit.html.DomNode) DomElement(com.gargoylesoftware.htmlunit.html.DomElement) HtmlPage(com.gargoylesoftware.htmlunit.html.HtmlPage) NicelyResynchronizingAjaxController(com.gargoylesoftware.htmlunit.NicelyResynchronizingAjaxController) SilentCssErrorHandler(com.gargoylesoftware.htmlunit.SilentCssErrorHandler) WebClient(com.gargoylesoftware.htmlunit.WebClient) HtmlInput(com.gargoylesoftware.htmlunit.html.HtmlInput) WebWindow(com.gargoylesoftware.htmlunit.WebWindow)

Example 5 with WebWindow

use of com.gargoylesoftware.htmlunit.WebWindow in project ats-framework by Axway.

the class HiddenHtmlElement method clickAndDownloadFile.

/**
 * Click the element and download file
 */
protected void clickAndDownloadFile() {
    WebWindow currentWindow = null;
    Field currentWindowField = null;
    boolean fieldAccessibleState = false;
    try {
        currentWindowField = htmlUnitDriver.getClass().getDeclaredField("currentWindow");
        fieldAccessibleState = currentWindowField.isAccessible();
        currentWindowField.setAccessible(true);
        currentWindow = (WebWindow) currentWindowField.get(htmlUnitDriver);
    } catch (Exception e) {
        throw new SeleniumOperationException("Error retrieving internal Selenium web client", e);
    } finally {
        if (currentWindowField != null) {
            currentWindowField.setAccessible(fieldAccessibleState);
        }
    }
    String elementXPath = properties.getProperty("xpath");
    // find element and download the file
    HtmlPage page = (HtmlPage) currentWindow.getEnclosedPage();
    List<?> foundElementsList = page.getByXPath(elementXPath);
    if (foundElementsList != null && !foundElementsList.isEmpty()) {
        InputStream in = null;
        FileOutputStream fos = null;
        try {
            com.gargoylesoftware.htmlunit.html.HtmlElement element = (com.gargoylesoftware.htmlunit.html.HtmlElement) foundElementsList.get(0);
            // Use generic Page. Exact page type returned depends on the MIME type set in response header
            Page result = element.click();
            String fileName = null;
            String contentDisposition = result.getWebResponse().getResponseHeaderValue("Content-Disposition");
            if (contentDisposition != null) {
                Matcher m = contentDispositionPattern.matcher(contentDisposition);
                if (m.matches()) {
                    fileName = m.group(1);
                    log.debug("Download file name extracted from the 'Content-Disposition' header is " + fileName);
                }
            }
            if (fileName == null) {
                String url = result.getWebResponse().getWebRequest().getUrl().getFile().trim();
                Matcher m = urlFileNamePattern.matcher(url);
                if (m.matches()) {
                    fileName = m.group(1);
                    log.debug("Download file name extracted from the request URL is " + fileName);
                } else {
                    fileName = String.valueOf(new Date().getTime()) + ".bin";
                    log.debug("Downloaded file name constructed the current timestamp is " + fileName);
                }
            }
            in = result.getWebResponse().getContentAsStream();
            String fileAbsPath = UiEngineConfigurator.getInstance().getBrowserDownloadDir() + fileName;
            fos = new FileOutputStream(new File(fileAbsPath), false);
            byte[] buff = new byte[BUFFER_LENGTH];
            int len;
            while ((len = in.read(buff)) != -1) {
                fos.write(buff, 0, len);
            }
            fos.flush();
            log.info("Downloaded file: " + fileAbsPath);
        } catch (IOException e) {
            throw new SeleniumOperationException("Error downloading file", e);
        } finally {
            IoUtils.closeStream(fos);
            IoUtils.closeStream(in);
        }
    } else {
        throw new ElementNotFoundException("Can't find element by XPath: " + elementXPath);
    }
}
Also used : HtmlPage(com.gargoylesoftware.htmlunit.html.HtmlPage) Matcher(java.util.regex.Matcher) InputStream(java.io.InputStream) HtmlElement(com.axway.ats.uiengine.elements.html.HtmlElement) HtmlPage(com.gargoylesoftware.htmlunit.html.HtmlPage) Page(com.gargoylesoftware.htmlunit.Page) ElementNotFoundException(com.axway.ats.uiengine.exceptions.ElementNotFoundException) IOException(java.io.IOException) SeleniumOperationException(com.axway.ats.uiengine.exceptions.SeleniumOperationException) SeleniumOperationException(com.axway.ats.uiengine.exceptions.SeleniumOperationException) ElementNotFoundException(com.axway.ats.uiengine.exceptions.ElementNotFoundException) IOException(java.io.IOException) Date(java.util.Date) WebWindow(com.gargoylesoftware.htmlunit.WebWindow) Field(java.lang.reflect.Field) FileOutputStream(java.io.FileOutputStream) File(java.io.File)

Aggregations

WebWindow (com.gargoylesoftware.htmlunit.WebWindow)7 HtmlPage (com.gargoylesoftware.htmlunit.html.HtmlPage)6 HtmlInput (com.gargoylesoftware.htmlunit.html.HtmlInput)3 File (java.io.File)3 WebClient (com.gargoylesoftware.htmlunit.WebClient)2 IOException (java.io.IOException)2 Test (org.junit.Test)2 HtmlElement (com.axway.ats.uiengine.elements.html.HtmlElement)1 ElementNotFoundException (com.axway.ats.uiengine.exceptions.ElementNotFoundException)1 SeleniumOperationException (com.axway.ats.uiengine.exceptions.SeleniumOperationException)1 NicelyResynchronizingAjaxController (com.gargoylesoftware.htmlunit.NicelyResynchronizingAjaxController)1 Page (com.gargoylesoftware.htmlunit.Page)1 SilentCssErrorHandler (com.gargoylesoftware.htmlunit.SilentCssErrorHandler)1 WebRequest (com.gargoylesoftware.htmlunit.WebRequest)1 DomElement (com.gargoylesoftware.htmlunit.html.DomElement)1 DomNode (com.gargoylesoftware.htmlunit.html.DomNode)1 HtmlElement (com.gargoylesoftware.htmlunit.html.HtmlElement)1 FileOutputStream (java.io.FileOutputStream)1 InputStream (java.io.InputStream)1 Field (java.lang.reflect.Field)1