WebClient client = new WebClient(); HtmlPage page = client.getPage("http://stackoverflow.com"); // create a submit button - it doesn't work with 'input' HtmlElement button = page.createElement("button"); button.setAttribute("type", "submit"); // append the button to the form HtmlElement form = ...; form.appendChild(button); // submit the form page = button.click();
@Test(groups = { "contexts" }) @SpecAssertion(section = "6.7.5", id = "id") public void testBeanWithDefaultQualifier() throws Exception { WebClient client = new WebClient(); HtmlPage page = client.getPage(getPath("builtin.jsf")); assert page.getBody().getTextContent().contains("Correct qualifier: true"); }
/** * Causes the web client to navigate to the current home page. Part of the * <tt>#default#homePage</tt> default IE behavior implementation. * @throws IOException if loading home page fails */ public void navigateHomePage() throws IOException { final WebClient webClient = getDomNodeOrDie().getPage().getEnclosingWindow().getWebClient(); webClient.getPage(webClient.getOptions().getHomePage()); }
/** * Returns the value of the <tt>background</tt> attribute. * @return the value of the <tt>background</tt> attribute * @see <a href="http://msdn.microsoft.com/en-us/library/ms533498.aspx">MSDN Documentation</a> */ public String jsxGet_background() { final HtmlElement node = getDomNodeOrDie(); String background = node.getAttribute("background"); if (background != DomElement.ATTRIBUTE_NOT_DEFINED && getBrowserVersion().isFirefox()) { try { final HtmlPage page = (HtmlPage) node.getPage(); background = page.getFullyQualifiedUrl(background).toExternalForm(); } catch (final MalformedURLException e) { Context.throwAsScriptRuntimeEx(e); } } return background; }
/** * 使用HtmlUnit获取页面内容,HtmlUnit能执行JS,动态渲染网页,但不是所有JS都能渲染,需要测试 * @param url html页面路径 * @return */ @Override public String fetch(String url) { try{ LOGGER.debug("url:"+url); HtmlPage htmlPage = WEB_CLIENT.getPage(url); String html = htmlPage.getBody().asXml(); LOGGER.debug("html:"+html); return html; }catch (Exception e) { LOGGER.error("获取URL:"+url+"页面出错", e); } return ""; }
/** * Submits the form (at the end of the current script execution). */ @JsxFunction public void submit() { final HtmlPage page = (HtmlPage) getDomNodeOrDie().getPage(); final WebClient webClient = page.getWebClient(); final String action = getHtmlForm().getActionAttribute().trim(); if (StringUtils.startsWithIgnoreCase(action, JavaScriptURLConnection.JAVASCRIPT_PREFIX)) { final String js = action.substring(JavaScriptURLConnection.JAVASCRIPT_PREFIX.length()); webClient.getJavaScriptEngine().execute(page, js, "Form action", 0); } else { // download should be done ASAP, response will be loaded into a window later final WebRequest request = getHtmlForm().getWebRequest(null); final String target = page.getResolvedTarget(getTarget()); final boolean forceDownload = webClient.getBrowserVersion().hasFeature(JS_FORM_SUBMIT_FORCES_DOWNLOAD); final boolean checkHash = !webClient.getBrowserVersion().hasFeature(FORM_SUBMISSION_DOWNLOWDS_ALSO_IF_ONLY_HASH_CHANGED); webClient.download(page.getEnclosingWindow(), target, request, checkHash, forceDownload, "JS form.submit()"); } }
final HtmlPage page = (HtmlPage) element.getDomNodeOrDie().getPage(); String uri = page.getUrl().toExternalForm(); try { final WebClient client = page.getWebClient(); if (link != null) { if (element.getBrowserVersion().hasFeature(HTMLLINK_CHECK_TYPE_FOR_STYLESHEET)) { final String type = link.getTypeAttribute(); if (StringUtils.isNotBlank(type) && !"text/css".equals(type)) { final String accept = client.getBrowserVersion().getCssAcceptHeader(); request = new WebRequest(new URL(url), accept); request.setAdditionalHeader(HttpHeader.REFERER, uri); response = client.loadWebResponse(request); final Cache cache = client.getCache(); final Object fromCache = cache.getCachedObject(request); if (fromCache instanceof org.w3c.dom.css.CSSStyleSheet) { throw Context.reportRuntimeError("Exception: " + e); throw Context.reportRuntimeError("Exception: " + e);
/** * Causes the web client to navigate to the current home page. Part of the * <tt>#default#homePage</tt> default IE behavior implementation. * @throws IOException if loading home page fails */ public void navigateHomePage() throws IOException { final WebClient webClient = getDomNodeOrDie().getPage().getEnclosingWindow().getWebClient(); webClient.getPage(webClient.getHomePage()); }
/** * Sets the object as active without setting focus to the object. * @see <a href="http://msdn.microsoft.com/en-us/library/ms536738.aspx">MSDN documentation</a> */ public void jsxFunction_setActive() { final Window window = getWindow(); final HTMLDocument document = window.jsxGet_document(); document.setActiveElement(this); if (window.getWebWindow() == window.getWebWindow().getWebClient().getCurrentWindow()) { final HtmlElement element = getDomNodeOrDie(); ((HtmlPage) element.getPage()).setFocusedElement(element); } }
else if (newElement != null && newElement.getPage() != this) { throw new IllegalArgumentException("Can't move focus to an element from an other page"); elementWithFocus_.fireEvent(Event.TYPE_FOCUS_OUT); newElement.fireEvent(Event.TYPE_FOCUS_IN); if (getWebClient().getBrowserVersion().hasFeature(BrowserVersionFeatures.BLUR_BEFORE_ONCHANGE)) { elementWithFocus_.fireEvent(Event.TYPE_BLUR); elementWithFocus_.removeFocus(); elementWithFocus_.removeFocus(); elementWithFocus_.fireEvent(Event.TYPE_BLUR); elementWithFocus_.focus(); newElement.fireEvent(Event.TYPE_FOCUS); return this == getEnclosingWindow().getEnclosedPage();
public class HtmlUnitTest { public static void main(String[] args) throws FailingHttpStatusCodeException, MalformedURLException, IOException { final WebClient webClient = new WebClient(); final HtmlPage page = webClient.getPage("http://www.google.com"); System.out.println(page.getTitleText()); for (HtmlElement node : page.getHtmlElementDescendants()) { if (node.getTagName().toUpperCase().equals("IMG")) { System.out.println("NAME: " + node.getTagName()); System.out.println("WIDTH:" + node.getAttribute("width")); System.out.println("HEIGHT:" + node.getAttribute("height")); System.out.println("TEXT: " + node.asText()); System.out.println("XMl: " + node.asXml()); } } } }
/** * {@inheritDoc} */ @Override @JsxGetter({CHROME, FF}) public String getVlinkColor() { String color = getPage().getBody().getAttribute("vLink"); if (color == DomElement.ATTRIBUTE_NOT_DEFINED && getBrowserVersion().hasFeature(HTMLDOCUMENT_COLOR)) { color = "#800080"; } if (getBrowserVersion().hasFeature(HTML_COLOR_EXPAND_ZERO) && "#0".equals(color)) { color = "#000000"; } return color; }
/** * Creates an instance. * * @param namespaceURI the URI that identifies an XML namespace * @param qualifiedName the qualified name of the element type to instantiate * @param page the page that contains this element * @param attributes a map ready initialized with the attributes for this element, or * <code>null</code>. The map will be stored as is, not copied. */ protected HtmlElement(final String namespaceURI, final String qualifiedName, final SgmlPage page, final Map<String, DomAttr> attributes) { super(namespaceURI, qualifiedName, page, attributes); if (page != null && page.getWebClient().getBrowserVersion().isFirefox()) { final String value = getAttribute("class"); if (value != ATTRIBUTE_NOT_DEFINED) { setAttribute("class", value.trim()); } } }
/** * Sets the focus on this element. */ public void focus() { ((HtmlPage) getPage()).setFocusedElement(this); final WebClient webClient = getPage().getWebClient(); if (webClient.getBrowserVersion().isIE()) { final HTMLElement jsElt = (HTMLElement) getScriptObject(); jsElt.jsxFunction_setActive(); } }
/** * Returns the value of the attribute {@code xml:lang}. Refer to the * <a href='http://www.w3.org/TR/html401/'>HTML 4.01</a> * documentation for details on the use of this attribute. * * @return the value of the attribute {@code xml:lang} or an empty string if that attribute isn't defined */ public final String getXmlLangAttribute() { return getAttribute("xml:lang"); }
final List<HtmlElement> elements = page.getElementsByName(name); if (elements.size() == 1) { result = getScriptableFor(elements.get(0)); final HtmlElement htmlElement = page.getHtmlElementById(name); result = getScriptableFor(htmlElement); result = new WindowProxy(webWindow); else if (result instanceof HTMLUnknownElement && getBrowserVersion().isIE()) { final HtmlElement unknownElement = ((HTMLUnknownElement) result).getDomNodeOrDie(); if (unknownElement.getNodeName().equals("xml")) { final XMLDocument document = ActiveXObject.buildXMLDocument(getWebWindow()); document.setParentScope(this); final Iterator<HtmlElement> children = unknownElement.getAllHtmlChildElements().iterator(); if (children.hasNext()) { final HtmlElement root = children.next(); document.jsxFunction_loadXML(root.asXml().trim());
final HtmlPage page = webClient.getPage("http://www.google.com"); HtmlElement inputField = page.getElementByName("q"); inputField.type("Example input"); HtmlElement btnG = page.getElementByName("btnG"); Page secondPage = btnG.click(); if (secondPage instanceof HtmlPage) { System.out.println(page.getTitleText()); System.out.println(((HtmlPage)secondPage).getTitleText()); }
/** * Sets the web client's current homepage. Part of the <tt>#default#homePage</tt> * default IE behavior implementation. * @param url the new homepage URL */ public void setHomePage(final String url) { getDomNodeOrDie().getPage().getEnclosingWindow().getWebClient().getOptions().setHomePage(url); }
/** * Returns the value of the <tt>bgColor</tt> attribute. * @return the value of the <tt>bgColor</tt> attribute * @see <a href="http://msdn.microsoft.com/en-us/library/ms533505.aspx">MSDN Documentation</a> */ public String jsxGet_bgColor() { String bgColor = getDomNodeOrDie().getAttribute("bgColor"); if (bgColor == DomElement.ATTRIBUTE_NOT_DEFINED && getBrowserVersion().isFirefox()) { bgColor = "#ffffff"; } return bgColor; }
/** * Replace all children elements of this element with the supplied value. * @param value - the new value for the contents of this node */ public void jsxSet_innerText(final String value) { final DomNode domNode = getDomNodeOrDie(); if (INNER_TEXT_READONLY.contains(domNode.getNodeName())) { throw Context.reportRuntimeError("innerText is read-only for tag " + domNode.getNodeName()); } domNode.removeAllChildren(); final DomNode node = new DomText(getDomNodeOrDie().getPage(), value); domNode.appendChild(node); //if the parentNode has null parentNode in IE, //create a DocumentFragment to be the parentNode's parentNode. if (domNode.getParentNode() == null && getBrowserVersion().isIE()) { final DomDocumentFragment fragment = ((HtmlPage) domNode.getPage()).createDomDocumentFragment(); fragment.appendChild(domNode); } }