@Test public void submittingForm() throws Exception { final WebClient webClient = new WebClient(); // Get the first page final HtmlPage page1 = webClient.getPage("http://some_url"); // Get the form that we are dealing with and within that form, // find the submit button and the field that we want to change. final HtmlForm form = page1.getFormByName("myform"); final HtmlSubmitInput button = form.getInputByName("submitbutton"); final HtmlTextInput textField = form.getInputByName("userid"); // Change the value of the text field textField.setValueAttribute("root"); // Now submit the form by clicking the button and get back the second page. final HtmlPage page2 = button.click(); webClient.closeAllWindows(); }
/** * Gets the title element for this page. Returns null if one is not found. * * @return the title element for this page or null if this is not one */ private HtmlTitle getTitleElement() { return (HtmlTitle) getFirstChildElementRecursive(getDocumentElement(), HtmlTitle.class); }
/** * {@inheritDoc} */ public HtmlElement getElementById(final String elementId) { try { return getHtmlElementById(elementId); } catch (final ElementNotFoundException e) { return null; } }
@Override public void runTest(TestRun run) throws IOException { if (++runs == 50) { runs = 0; cleanUp(); init(); } try { page.set(webClient.get().getPage("about:blank")); } catch (IOException e) { throw new RuntimeException(e); } HtmlPage pageRef = page.get(); pageRef.executeJavaScript(readFile(new File(run.getBaseDirectory(), run.getFileName()))); boolean decodeStack = Boolean.parseBoolean(System.getProperty(TeaVMTestRunner.JS_DECODE_STACK, "true")); File debugFile = decodeStack ? new File(run.getBaseDirectory(), run.getFileName() + ".teavmdbg") : null; RhinoResultParser resultParser = new RhinoResultParser(debugFile); AsyncResult asyncResult = new AsyncResult(); Function function = (Function) page.get().executeJavaScript(readResource("teavm-htmlunit-adapter.js")) .getJavaScriptResult(); Object[] args = new Object[] { decodeStack ? createStackDecoderFunction(resultParser) : null, new NativeJavaObject(function, asyncResult, AsyncResult.class) }; pageRef.executeJavaScriptFunction(function, function, args, page.get()); resultParser.parseResult((Scriptable) asyncResult.getResult(), run.getCallback()); }
public List<ConfigsBean> fetch(WebClient webClient) throws IOException { final HtmlPage page = webClient.getPage(HOME_PAGE); DomNodeList<DomElement> domNodeList = page.getElementsByTagName("a"); HtmlPage tempPage = null; try { webClient.waitForBackgroundJavaScript(500); tempPage = domElement.click(); Thread.sleep(500); DomElement surge_url = tempPage.getElementById("surge_url"); if (surge_url != null) { String href = surge_url.getAttribute("href");
/** * Tests that an anonymous object can be bound. */ public void testAnonymousBind() throws Exception { WebClient wc = new WebClient(); HtmlPage page = wc.getPage(new URL(url, "/bindAnonymous")); page.executeJavaScript("v.xyz('hello');"); assertEquals("hello",anonymousValue); }
@SuppressWarnings("deprecation") private String getRefreshToken() { webClient.getOptions().setRedirectEnabled(false); authPage = webClient.getPage(url); } catch (FailingHttpStatusCodeException e) { authPage = webClient.getPage(location); done = true; } catch (FailingHttpStatusCodeException e1) { final HtmlDivision div = authPage.getFirstByXPath("//div[@role='alert']"); if (div != null) { throw new IllegalArgumentException("Error authorizing application: " + div.getTextContent()); final HtmlForm loginForm = authPage.getForms().get(0); final HtmlTextInput login = loginForm.getInputByName("session_key"); login.setText(oAuthParams.getUserName()); try { final Page redirectPage = submitInput.click(); redirectQuery = redirectPage.getUrl().getQuery(); } catch (FailingHttpStatusCodeException e) { throw e; final String location = e.getResponse().getResponseHeaderValue("Location"); redirectQuery = new URL(location).getQuery();
HtmlPage currentPage = (HtmlPage) webClient.getPage(newURL("http://www.animewallpapers.com")); @SuppressWarnings("unchecked") List<HtmlImage> urls = (List<HtmlImage>) currentPage.getByXPath("//img"); for(int i = 0; i < 500; i++){ currentPage = (HtmlPage) webClient.getPage(new URL(urls.get(i).toString())); @SuppressWarnings("unchecked") List<HtmlImage> tempListUrls = (List<HtmlImage>) currentPage.getByXPath("//img");
public void testMainFeature() throws Exception { WebClient wc = new WebClient(); HtmlPage page = wc.getPage(new URL(url, "/form.html")); HtmlForm f = page.getFormByName("main"); f.getInputByName("json").setValueAttribute("{\"first\":\"Kohsuke\",\"last\":\"Kawaguchi\"}"); f.submit(); }
@Test public void testELWithParameters(@ArquillianResource URL baseURL) throws Exception { WebClient client = new WebClient(); HtmlPage page = client.getPage(new URL(baseURL, "charlie.jsf")); page.asXml(); HtmlSpan oldel = getFirstMatchingElement(page, HtmlSpan.class, "oldel"); assertNotNull(oldel); final String charlie = "Charlie"; assertEquals(charlie, oldel.asText()); HtmlSpan newel = getFirstMatchingElement(page, HtmlSpan.class, "newel"); assertNotNull(newel); assertEquals(charlie, newel.asText()); }
WebClient wc = new WebClient(); URL url = new URL("http://www.oogly.co.uk/"); HtmlPage page = (HtmlPage) wc.getPage(url); PrintWriter printWriter = new PrintWriter(new FileWriter(FILE_NAME)); List anchors = page.getAnchors();
URL url = new URL("http://www.example.com"); StringWebResponse response = new StringWebResponse("<html><head><title>Test</title></head><body></body></html>", url); HtmlPage page = HTMLParser.parseHtml(response, new TopLevelWindow("top", new WebClient())); System.out.println(page.getTitleText());
WebClient webClient = new WebClient(); WebRequest wr = new WebRequest(new URL("http://url.to.post"), HttpMethod.POST); List<NameValuePair> parameters = Arrays.asList( new NameValuePair("name", "john"), new NameValuePair("age", "28")); wr.setRequestParameters(parameters); HtmlPage page = webClient.getPage(wr); System.out.println(page.asXml());
final HtmlPage page = (HtmlPage) getWindow(getStartingScope()).getWebWindow().getEnclosedPage(); if (newLocation.startsWith(JavaScriptURLConnection.JAVASCRIPT_PREFIX)) { final String script = newLocation.substring(11); page.executeJavaScript(script, "new location value", 1); return; URL url = page.getFullyQualifiedUrl(newLocation); final boolean dropFilename = page.getWebClient().getBrowserVersion(). hasFeature(ANCHOR_EMPTY_HREF_NO_FILENAME); if (dropFilename) { String path = url.getPath(); path = path.substring(0, path.lastIndexOf('/') + 1); url = UrlUtils.getUrlWithNewPath(url, path); request.setAdditionalHeader(HttpHeader.REFERER, page.getUrl().toExternalForm()); webWindow.getWebClient().download(webWindow, "", request, true, false, "JS set location");
@Override protected String getCallbackUrl(final HtmlPage authorizationPage) throws Exception { final HtmlForm form = authorizationPage.getForms().get(0); final HtmlTextInput email = form.getInputByName("email"); email.setValueAttribute("testscribeup@gmail.com"); final HtmlPasswordInput password = form.getInputByName("pass"); password.setValueAttribute("testpwdscribeup"); final HtmlSubmitInput submit = form.getInputByName("login"); final HtmlPage callbackPage = submit.click(); final String callbackUrl = callbackPage.getUrl().toString(); logger.debug("callbackUrl : {}", callbackUrl); return callbackUrl; }
final boolean ie = getPage().getWebClient().getBrowserVersion().isIE(); if (!executeIfDeferred && isDeferred() && ie) { return; final Window window = (Window) getPage().getEnclosingWindow().getScriptObject(); final BaseFunction function = new EventHandler(this, event, scriptCode); window.jsxFunction_attachEvent(event, function); final HtmlElement elt = ((HtmlPage) getPage()).getHtmlElementById(forr); elt.setEventHandler(event, scriptCode); final String url = getPage().getWebResponse().getRequestSettings().getUrl().toExternalForm(); final int line1 = getStartLineNumber(); final int line2 = getEndLineNumber(); final String desc = "script in " + url + " from (" + line1 + ", " + col1 + ") to (" + line2 + ", " + col2 + ")"; ((HtmlPage) getPage()).executeJavaScriptIfPossible(scriptCode, desc, line1);
private WebResponse makeWebResponseForJavaScriptUrl(final WebWindow webWindow, final URL url, final Charset charset) throws FailingHttpStatusCodeException, IOException { HtmlPage page = null; if (webWindow instanceof FrameWindow) { final FrameWindow frameWindow = (FrameWindow) webWindow; page = (HtmlPage) frameWindow.getEnclosedPage(); } else { final Page currentPage = webWindow.getEnclosedPage(); if (currentPage instanceof HtmlPage) { page = (HtmlPage) currentPage; } } if (page == null) { page = getPage(webWindow, new WebRequest(WebClient.URL_ABOUT_BLANK)); } final ScriptResult r = page.executeJavaScript(url.toExternalForm(), "JavaScript URL", 1); if (r.getJavaScriptResult() == null || ScriptResult.isUndefined(r)) { // No new WebResponse to produce. return webWindow.getEnclosedPage().getWebResponse(); } final String contentString = r.getJavaScriptResult().toString(); final StringWebResponse response = new StringWebResponse(contentString, charset, url); response.setFromJavascript(true); return response; }
HtmlPage page = (HtmlPage) currentWindow.getEnclosedPage(); List<?> foundElementsList = page.getByXPath(elementXPath); if (foundElementsList != null && !foundElementsList.isEmpty()) { try { com.gargoylesoftware.htmlunit.html.HtmlElement element = (com.gargoylesoftware.htmlunit.html.HtmlElement) foundElementsList.get(0); Page result = element.click(); // Use generic Page. Exact page type returned depends on the MIME type set in response header .getResponseHeaderValue("Content-Disposition"); if (contentDisposition != null) { Matcher m = contentDispositionPattern.matcher(contentDisposition); String url = result.getWebResponse().getWebRequest().getUrl().getFile().trim(); Matcher m = urlFileNamePattern.matcher(url); if (m.matches()) { in = result.getWebResponse().getContentAsStream(); String fileAbsPath = UiEngineConfigurator.getInstance().getBrowserDownloadDir() + fileName; fos = new FileOutputStream(new File(fileAbsPath), false);
/** * Runs the sanity check. * @throws Exception if anything goes wrong */ private static void runSanityCheck() throws Exception { try (WebClient webClient = new WebClient()) { final HtmlPage page = webClient.getPage("http://htmlunit.sourceforge.net/index.html"); page.executeJavaScript("document.location"); System.out.println("Sanity check complete."); } }
try (WebClient webClient = new WebClient(BrowserVersion.CHROME)) { new WebConnectionWrapper(webClient) { public WebResponse getResponse(WebRequest request) throws IOException { WebResponse response = super.getResponse(request); if (request.getUrl().toExternalForm().endsWith("identifier_select")) { String content = response.getContentAsString("UTF-8"); content = content.replace(">$J( function()", "$J( function()"); WebResponseData data = new WebResponseData(content.getBytes("UTF-8"), response.getStatusCode(), response.getStatusMessage(), response.getResponseHeaders()); response = new WebResponse(data, request, response.getLoadTime()); } return response; } }; HtmlPage page = webClient.getPage("http://www.tf2outpost.com"); HtmlAnchor a = page.getAnchorByHref("/login"); page = a.click(); page.<HtmlInput>getHtmlElementById("steamAccountName").setValueAttribute(username); page.<HtmlInput>getHtmlElementById("steamPassword").setValueAttribute(password); page = page.<HtmlInput>getHtmlElementById("imageLogin").click(); webClient.waitForBackgroundJavaScript(5000); System.out.println(page.asXml());