java 如何从字符串创建 HtmlUnit HTMLPage 对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6136435/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create HtmlUnit HTMLPage object from String?
提问by lisak
This question was asked once already, but the API changed I guess and the answers are no valid anymore.
这个问题已经被问过一次,但我猜 API 改变了,答案不再有效。
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());
Can't be done because TopLevelWindow is protected and stuff like extending/implementing the window because of that is ridiculous :)
无法完成,因为 TopLevelWindow 受到保护,因此扩展/实现窗口之类的东西很荒谬:)
Anybody has an idea how to do that ? It seems to me weird that it can't be done easily.
有人知道怎么做吗?在我看来很奇怪,这不容易完成。
回答by Grooveek
This code works in GroovyConsole
此代码适用于 GroovyConsole
@Grapes(
@Grab(group='net.sourceforge.htmlunit', module='htmlunit', version='2.8')
)
import com.gargoylesoftware.htmlunit.*
import com.gargoylesoftware.htmlunit.html.*
URL url = new URL("http://www.example.com");
StringWebResponse response = new StringWebResponse("<html><head><title>Test</title></head><body></body></html>", url);
WebClient client = new WebClient()
HtmlPage page = HTMLParser.parseHtml(response, client.getCurrentWindow());
System.out.println(page.getTitleText());