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);
}
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);
}
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);
}
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();
}
}
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);
}
}
Aggregations