下面列出了怎么用com.gargoylesoftware.htmlunit.html.DomElement的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Search for the namespace URI of the given prefix, starting from the specified element.
* The default namespace can be searched for by specifying "" as the prefix.
* @param element the element to start searching from
* @param prefix the namespace prefix
* @return the namespace URI bound to the prefix; or null if there is no such namespace
*/
public static String lookupNamespaceURI(final DomElement element, final String prefix) {
String uri = DomElement.ATTRIBUTE_NOT_DEFINED;
if (prefix.isEmpty()) {
uri = element.getAttributeDirect("xmlns");
}
else {
uri = element.getAttribute("xmlns:" + prefix);
}
if (uri == DomElement.ATTRIBUTE_NOT_DEFINED) {
final DomNode parentNode = element.getParentNode();
if (parentNode instanceof DomElement) {
uri = lookupNamespaceURI((DomElement) parentNode, prefix);
}
}
return uri;
}
/**
* Returns the value of the attribute.
* @param name the name of the attribute to return
* @return the value of the specified attribute, {@code null} if the named attribute does not have a
* specified value
*/
@JsxFunction
public Object getAttribute(final String name) {
if (name == null || "null".equals(name)) {
throw Context.reportRuntimeError("Type mismatch.");
}
if (StringUtils.isEmpty(name)) {
throw Context.reportRuntimeError("The empty string '' is not a valid name.");
}
final String value = getDomNodeOrDie().getAttribute(name);
if (value == DomElement.ATTRIBUTE_NOT_DEFINED) {
return null;
}
return value;
}
/**
* Dispatches an event into the event system (standards-conformant browsers only). See
* <a href="https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/dispatchEvent">the Gecko
* DOM reference</a> for more information.
*
* @param event the event to be dispatched
* @return {@code false} if at least one of the event handlers which handled the event
* called <tt>preventDefault</tt>; {@code true} otherwise
*/
@JsxFunction
public boolean dispatchEvent(final Event event) {
event.setTarget(this);
final DomElement element = (DomElement) getDomNodeOrNull();
ScriptResult result = null;
if (event.getType().equals(MouseEvent.TYPE_CLICK)) {
try {
element.click(event, true);
}
catch (final IOException e) {
throw Context.reportRuntimeError("Error calling click(): " + e.getMessage());
}
}
else {
result = fireEvent(event);
}
return !event.isAborted(result);
}
/**
* Returns true if the element would be selected by the specified selector string; otherwise, returns false.
* @param context the JavaScript context
* @param thisObj the scriptable
* @param args the arguments passed into the method
* @param function the function
* @return the value
*/
@JsxFunction({CHROME, FF, FF68, FF60})
public static boolean matches(
final Context context, final Scriptable thisObj, final Object[] args, final Function function) {
final String selectorString = (String) args[0];
if (!(thisObj instanceof Element)) {
throw ScriptRuntime.typeError("Illegal invocation");
}
try {
final DomNode domNode = ((Element) thisObj).getDomNodeOrNull();
return domNode != null && ((DomElement) domNode).matches(selectorString);
}
catch (final CSSException e) {
throw ScriptRuntime.constructError("SyntaxError",
"An invalid or illegal selector was specified (selector: '"
+ selectorString + "' error: " + e.getMessage() + ").");
}
}
/**
* Search for the namespace URI of the given prefix, starting from the specified element.
* The default namespace can be searched for by specifying "" as the prefix.
* @param element the element to start searching from
* @param prefix the namespace prefix
* @return the namespace URI bound to the prefix; or null if there is no such namespace
*/
public static String lookupNamespaceURI(final DomElement element, final String prefix) {
String uri = DomElement.ATTRIBUTE_NOT_DEFINED;
if (prefix.isEmpty()) {
uri = element.getAttributeDirect("xmlns");
}
else {
uri = element.getAttribute("xmlns:" + prefix);
}
if (uri == DomElement.ATTRIBUTE_NOT_DEFINED) {
final DomNode parentNode = element.getParentNode();
if (parentNode instanceof DomElement) {
uri = lookupNamespaceURI((DomElement) parentNode, prefix);
}
}
return uri;
}
/**
* {@inheritDoc}
*/
@Override
public MSXMLScriptable makeScriptableFor(final DomNode domNode) {
final MSXMLScriptable scriptable;
if (domNode instanceof DomElement && !(domNode instanceof HtmlElement)) {
scriptable = new XMLDOMElement();
}
else if (domNode instanceof DomAttr) {
scriptable = new XMLDOMAttribute();
}
else {
return (MSXMLScriptable) super.makeScriptableFor(domNode);
}
scriptable.setParentScope(this);
scriptable.setPrototype(getPrototype(scriptable.getClass()));
scriptable.setDomNode(domNode);
return scriptable;
}
/**
* Adds the ids of the collection's elements to the idList.
* @param idList the list to add the ids to
* @param elements the collection's elements
*/
protected void addElementIds(final List<String> idList, final List<DomNode> elements) {
int index = 0;
for (final DomNode next : elements) {
final HtmlElement element = (HtmlElement) next;
final String name = element.getAttributeDirect("name");
if (name != DomElement.ATTRIBUTE_NOT_DEFINED) {
idList.add(name);
}
else {
final String id = element.getId();
if (id != DomElement.ATTRIBUTE_NOT_DEFINED) {
idList.add(id);
}
else {
idList.add(Integer.toString(index));
}
}
index++;
}
}
/**
* Adds the ids of the collection's elements to the idList.
* @param idList the list to add the ids to
* @param elements the collection's elements
*/
protected void addElementIds(final List<String> idList, final List<DomNode> elements) {
int index = 0;
for (final DomNode next : elements) {
if (next instanceof DomElement) {
final DomElement element = (DomElement) next;
final String name = element.getAttributeDirect("name");
if (name != DomElement.ATTRIBUTE_NOT_DEFINED) {
idList.add(name);
}
final String id = element.getId();
if (id != DomElement.ATTRIBUTE_NOT_DEFINED) {
idList.add(id);
}
}
if (!getBrowserVersion().hasFeature(JS_NODE_LIST_ENUMERATE_FUNCTIONS)) {
idList.add(Integer.toString(index));
}
index++;
}
}
/**
* Search for the prefix associated with specified namespace URI.
* @param element the element to start searching from
* @param namespace the namespace prefix
* @return the prefix bound to the namespace URI; or null if there is no such namespace
*/
public static String lookupPrefix(final DomElement element, final String namespace) {
final Map<String, DomAttr> attributes = element.getAttributesMap();
for (final Map.Entry<String, DomAttr> entry : attributes.entrySet()) {
final String name = entry.getKey();
final DomAttr value = entry.getValue();
if (name.startsWith("xmlns:") && value.getValue().equals(namespace)) {
return name.substring(6);
}
}
for (final DomNode child : element.getChildren()) {
if (child instanceof DomElement) {
final String prefix = lookupPrefix((DomElement) child, namespace);
if (prefix != null) {
return prefix;
}
}
}
return null;
}
/**
* Gets the children of the current node.
* @see <a href="http://msdn.microsoft.com/en-us/library/ms537446.aspx">MSDN documentation</a>
* @return the child at the given position
*/
protected HTMLCollection getChildren() {
final DomNode node = getDomNodeOrDie();
final HTMLCollection collection = new HTMLCollection(node, false) {
@Override
protected List<DomNode> computeElements() {
final List<DomNode> children = new LinkedList<>();
for (DomNode domNode : node.getChildNodes()) {
if (domNode instanceof DomElement) {
children.add(domNode);
}
}
return children;
}
};
return collection;
}
/**
* Returns the value of this link's {@code href} property.
* @return the value of this link's {@code href} property
*/
@JsxGetter
public String getHref() {
final HtmlAnchor anchor = (HtmlAnchor) getDomNodeOrDie();
final String hrefAttr = anchor.getHrefAttribute();
if (hrefAttr == DomElement.ATTRIBUTE_NOT_DEFINED) {
return "";
}
try {
return getUrl().toString();
}
catch (final MalformedURLException e) {
return hrefAttr;
}
}
private String getNamespace(final DomElement element, final String prefix) {
final Map<String, DomAttr> attributes = element.getAttributesMap();
final String xmlns = "xmlns:";
final int xmlnsLength = xmlns.length();
for (final Map.Entry<String, DomAttr> entry : attributes.entrySet()) {
final String name = entry.getKey();
if (name.startsWith(xmlns) && name.regionMatches(xmlnsLength, prefix, 0, prefix.length())) {
return entry.getValue().getValue();
}
}
for (final DomNode child : element.getChildren()) {
if (child instanceof DomElement) {
final String namespace = getNamespace((DomElement) child, prefix);
if (namespace != null) {
return namespace;
}
}
}
return null;
}
/**
* Adds the ids of the collection's elements to the idList.
* @param idList the list to add the ids to
* @param elements the collection's elements
*/
protected void addElementIds(final List<String> idList, final List<DomNode> elements) {
int index = 0;
for (final DomNode next : elements) {
if (next instanceof DomElement) {
final DomElement element = (DomElement) next;
final String name = element.getAttributeDirect("name");
if (name != DomElement.ATTRIBUTE_NOT_DEFINED) {
idList.add(name);
}
final String id = element.getId();
if (id != DomElement.ATTRIBUTE_NOT_DEFINED) {
idList.add(id);
}
}
if (!getBrowserVersion().hasFeature(JS_NODE_LIST_ENUMERATE_FUNCTIONS)) {
idList.add(Integer.toString(index));
}
index++;
}
}
private String getNamespace(final DomElement element, final String prefix) {
final Map<String, DomAttr> attributes = element.getAttributesMap();
final String xmlns = "xmlns:";
final int xmlnsLength = xmlns.length();
for (final Map.Entry<String, DomAttr> entry : attributes.entrySet()) {
final String name = entry.getKey();
if (name.startsWith(xmlns) && name.regionMatches(xmlnsLength, prefix, 0, prefix.length())) {
return entry.getValue().getValue();
}
}
for (final DomNode child : element.getChildren()) {
if (child instanceof DomElement) {
final String namespace = getNamespace((DomElement) child, prefix);
if (namespace != null) {
return namespace;
}
}
}
return null;
}
private static List<DomNode> getItComputeElements(final HtmlPage page, final String name,
final boolean forIDAndOrName, final boolean alsoFrames) {
final List<DomElement> elements;
if (forIDAndOrName) {
elements = page.getElementsByIdAndOrName(name);
}
else {
elements = page.getElementsByName(name);
}
final List<DomNode> matchingElements = new ArrayList<>();
for (final DomElement elt : elements) {
if (elt instanceof HtmlForm || elt instanceof HtmlImage || elt instanceof HtmlApplet
|| (alsoFrames && elt instanceof BaseFrameElement)) {
matchingElements.add(elt);
}
}
return matchingElements;
}
/**
* @throws Exception if something goes wrong
*/
@Test
public void appendChildMoved() throws Exception {
final String html = "<html>\n"
+ "<head><title>foo</title></head>\n"
+ "<body>\n"
+ "<p>hello</p>\n"
+ "</body></html>";
final String html2 = "<html>\n"
+ "<head><title>foo</title></head>\n"
+ "<body>\n"
+ "<p id='tester'>world</p>\n"
+ "</body></html>";
try (WebClient webClient = new WebClient(getBrowserVersion(), false, null, -1)) {
final HtmlPage page = loadPage(webClient, html, null, URL_FIRST);
final HtmlPage page2 = loadPage(webClient, html2, null, URL_SECOND);
final DomNodeList<DomElement> elements = page.getElementsByTagName("*");
assertEquals(5, elements.getLength());
page.getBody().appendChild(page2.getElementById("tester"));
assertEquals(6, elements.getLength());
}
}
@Ignore
@Test
// TODO: This method of testing does not work for angular, need to find an alternative method of testing
public void techFormTest() {
final WebClient webClient = new WebClient(BrowserVersion.CHROME);
HtmlPage page;
String port = System.getProperty("liberty.test.port");
try {
page = webClient.getPage("http://localhost:" + port + "/start/");
DomElement techForm = page.getElementById("techTable");
DomElement formBody = techForm.getFirstElementChild();
int count = formBody.getChildElementCount();
// We expect there to be more than one child element, otherwise the
// javascript has not created the tech table properly.
assertTrue("Expected more than one element in the tech table, instead found " + count, count > 1);
} catch (Exception e){
org.junit.Assert.fail("Caught exception: " + e.getCause().toString());
} finally {
webClient.close();
}
}
/**
* Returns the element with the specified ID, as long as it is an HTML element; {@code null} otherwise.
* @param id the ID to search for
* @return the element with the specified ID, as long as it is an HTML element; {@code null} otherwise
*/
@JsxFunction
public Object getElementById(final String id) {
final DomNode domNode = getDomNodeOrDie();
final Object domElement = domNode.getFirstByXPath("//*[@id = \"" + id + "\"]");
if (domElement != null) {
if (!(domNode instanceof XmlPage) || domElement instanceof HtmlElement
|| getBrowserVersion().hasFeature(JS_XML_GET_ELEMENT_BY_ID__ANY_ELEMENT)) {
return ((DomElement) domElement).getScriptableObject();
}
if (LOG.isDebugEnabled()) {
LOG.debug("getElementById(" + id + "): no HTML DOM node found with this ID");
}
}
return null;
}
static String getDefaultValue(final HtmlElement element) {
String href = element.getAttributeDirect("href");
if (DomElement.ATTRIBUTE_NOT_DEFINED == href) {
return ""; // for example for named anchors
}
href = href.trim();
final SgmlPage page = element.getPage();
if (page == null || !page.isHtmlPage()) {
return href;
}
try {
return HtmlAnchor.getTargetUrl(href, (HtmlPage) page).toExternalForm();
}
catch (final MalformedURLException e) {
return href;
}
}
@org.junit.Test
public void testSuccessfulInvokeOnIdP() throws Exception {
String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?";
url += "wa=wsignin1.0";
url += "&whr=urn:org:apache:cxf:fediz:idp:realm-A";
url += "&wtrealm=urn:org:apache:cxf:fediz:fedizhelloworld";
String wreply = "https://localhost:" + getRpHttpsPort() + "/" + getServletContextName() + "/secure/fedservlet";
url += "&wreply=" + wreply;
String user = "alice";
String password = "ecila";
final WebClient webClient = new WebClient();
webClient.getOptions().setUseInsecureSSL(true);
webClient.getCredentialsProvider().setCredentials(
new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())),
new UsernamePasswordCredentials(user, password));
webClient.getOptions().setJavaScriptEnabled(false);
final HtmlPage idpPage = webClient.getPage(url);
webClient.getOptions().setJavaScriptEnabled(true);
Assert.assertEquals("IDP SignIn Response Form", idpPage.getTitleText());
// Parse the form to get the token (wresult)
DomNodeList<DomElement> results = idpPage.getElementsByTagName("input");
String wresult = null;
for (DomElement result : results) {
if ("wresult".equals(result.getAttributeNS(null, "name"))) {
wresult = result.getAttributeNS(null, "value");
break;
}
}
Assert.assertNotNull(wresult);
webClient.close();
}
/**
* Test for a strange error we found: An ajax running
* in parallel shares the additional headers with a form
* submit.
*
* @throws Exception if an error occurs
*/
@Test
public void ajaxInfluencesSubmitHeaders() throws Exception {
final Map<String, Class<? extends Servlet>> servlets = new HashMap<>();
servlets.put("/content.html", ContentServlet.class);
servlets.put("/ajax_headers.html", AjaxHeaderServlet.class);
servlets.put("/form_headers.html", FormHeaderServlet.class);
startWebServer("./", null, servlets);
collectedHeaders_.clear();
XMLHttpRequest3Test.STATE_ = 0;
final WebClient client = getWebClient();
final List<String> collectedAlerts = Collections.synchronizedList(new ArrayList<String>());
client.setAlertHandler(new CollectingAlertHandler(collectedAlerts));
final HtmlPage page = client.getPage(URL_FIRST + "content.html");
final DomElement elem = page.getElementById("doIt");
while (STATE_ < 1) {
Thread.sleep(42);
}
((HtmlSubmitInput) elem).click();
client.waitForBackgroundJavaScript(DEFAULT_WAIT_TIME);
assertEquals(collectedHeaders_.toString(), 2, collectedHeaders_.size());
String headers = collectedHeaders_.get(0);
if (!headers.startsWith("Form: ")) {
headers = collectedHeaders_.get(1);
}
assertTrue(headers, headers.startsWith("Form: "));
assertFalse(headers, headers.contains("Html-Unit=is great,;"));
headers = collectedHeaders_.get(0);
if (!headers.startsWith("Ajax: ")) {
headers = collectedHeaders_.get(1);
}
assertTrue(headers, headers.startsWith("Ajax: "));
assertTrue(headers, headers.contains("Html-Unit=is great,;"));
}
/**
* Returns the owner element.
* @return the owner element
*/
@JsxGetter
public Object getOwnerElement() {
final DomElement parent = getDomNodeOrDie().getOwnerElement();
if (parent != null) {
return parent.getScriptableObject();
}
return null;
}
/** {@inheritDoc} */
@Override
protected void runJavaScript(final HtmlPage page) {
final DomElement doc = page.getDocumentElement();
final Scriptable scriptable = page.getEnclosingWindow().getScriptableObject();
page.executeJavaScriptFunction(function_, scriptable, new Object[0], doc);
}
private List<String> getLinksWithGivenTargetName(final HtmlPage page, final String targetName) {
List<DomElement> htmlElement = page.getElementsByIdAndOrName(targetName);
ArrayList<String> links = new ArrayList<>();
for (DomElement element : htmlElement) {
DomNodeList<HtmlElement> domNodeList = element.getElementsByTagName("a");
for (HtmlElement htmlElementHref : domNodeList) {
links.add(htmlElementHref.getAttribute("href"));
}
}
return links;
}
private HtmlPage click(DomElement button) {
try {
return button.click();
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
@Test
public void shouldNotSeeMigrationButton() throws IOException, SAXException {
JenkinsRule.WebClient webClient = jenkinsRule.createWebClient();
DomElement configureSection = webClient.goTo("configure").getElementsByName("AwsCodeCommitTriggerPlugin").get(0);
List<?> buttons = configureSection.getByXPath("//button[contains(.,'Migration')]");
Assertions.assertThat(buttons).isEmpty();
}
/**
* Returns the previous element sibling.
* @return the previous element sibling
*/
@JsxGetter({CHROME, FF})
public Element getPreviousElementSibling() {
final DomElement child = getDomNodeOrDie().getPreviousElementSibling();
if (child != null) {
return (Element) child.getScriptableObject();
}
return null;
}
private static List<DomElement> getElementsByNameWithoutJdk(HtmlPage page, String name) {
String jdkCheckUrl = "/jenkins/descriptorByName/hudson.model.JDK/checkName";
List<DomElement> r = new ArrayList<>();
for (DomElement domElement : page.getElementsByName(name)) {
if (!jdkCheckUrl.equals(domElement.getAttribute("checkurl"))) {
r.add(domElement);
}
}
return r;
}
@Test
@RunAsClient
public void test() throws Exception {
final HtmlPage page = webClient.getPage(baseURL + "resources/hello?user=mvc");
final DomElement h1 = page.getElementsByTagName("h1").get(0);
assertNotNull(h1);
assertTrue(h1.getTextContent().contains("mvc"));
}
/**
* Returns the next element sibling.
* @return the next element sibling
*/
@JsxGetter
public Element getNextElementSibling() {
final DomElement child = getDomNodeOrDie().getNextElementSibling();
if (child != null) {
return (Element) child.getScriptableObject();
}
return null;
}