如何使用 htmlunit 更新 html 中的内容?
我发现使用 htmlunit 来动态创建新的 html 内容非常困难,就像我们在 jquery 中所做的那样。
例如给定一个文本节点:
I am text
我想将该文本节点更改为(如果单词大于 3 个字符,则将其替换 with span):
I am <span>text</span>
此后我想用
I am <span>text</span>
html 文档中出现的原始文本节点(我是文本)替换它。
那么如何使用 htmlunit 来实现这一点呢?在 Java 应用程序中,是否有更好的 htmlunit 替代方案来进行屏幕抓取或动态修改 dom 类型的应用程序?
在 htmlunit 中,我什至找不到如何构造新元素,因为构造函数大多丢失或声明为受保护的。
I found it very difficult to work with htmlunit in terms of creating new html content on the fly like we can do in jquery.
For example given a text node:
I am text
I want change that text node into (if the word is greater than 3 chars it is replaced
with span):
I am <span>text</span>
After this I want to replace the original text node ( I am text) with
I am <span>text</span>
in the html document wherever it occurred.
So how can I achieve this using htmlunit? Is there better alternative to htmlunit in Java applications for screen scraping or modify dom on the fly type of applications?
In htmlunit I could not even find how to construct a new element as constructors are mostly missing or declared protected.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
目前尚不清楚您到底想做什么,但 HtmlUnit 是一个编程浏览器。它的 API 允许在 Java 中执行用户在标准浏览器中使用键盘和鼠标执行的操作。修改网页的 DOM 并不是用户使用浏览器所做的事情。
无论如何,它的 API 都允许访问 DOM 树(尽管不是通过 W3C DOM 接口),因此您应该能够在 Java 中执行在 JavaScript 中使用 DOM 执行的操作。
HtmlElement
实例可以通过HtmlPage
的 createElement 方法。但当然,不存在“JQuery in Java for HtmlUnit”。It's not clear what you want to do exactly, but HtmlUnit is a programmatic browser. Its API allows doing in Java what a user would do with his keyboard and mouse in a standard browser. And modifying the DOM of a web page is not what a user does with his browser.
Its API allows accessing the DOM tree anyway (though not via the W3C DOM interfaces), and you should thus be able to do in Java what you would do in JavaScript with the DOM.
HtmlElement
instances can be created through the createElement method ofHtmlPage
. But of course, there is no "JQuery in Java for HtmlUnit".HtmlUnit 允许您在页面上下文中运行 JS 脚本。例如:
newPage 将是您的脚本修改的原始页面的副本。
HtmlUnit allows you to run JS script in context of a page. Like:
newPage will be a copy of original page modified by your script.
HtmlUnit 允许您通过 Java 与页面交互,这与人类通过浏览器与页面交互的方式大致相同。
您将如何在浏览器中修改 DOM?
您不会,不是直接修改:而是单击或键入以在页面中触发 Javascript,从而修改 DOM。同样,使用 HtmlUnit,您的 Java 代码会触发页面中的 Javascript,从而修改 DOM。
HtmlUnit lets you interact with a page via Java roughly the same way a human would interact with the page via a browser.
How would you modify the DOM in a browser?
You don't, not directly: instead you click or type to trigger Javascript in the page, which in turn modifies the DOM. Likewise, with HtmlUnit your Java code triggers Javascript in the page which in turn modifies the DOM.