How to create HtmlUnit HTMLPage object from String?

[亡魂溺海] 提交于 2019-11-29 06:10:55

问题


This question was asked once already, but the API changed I guess and the answers are no valid anymore.

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 :)

Anybody has an idea how to do that ? It seems to me weird that it can't be done easily.


回答1:


This code works in 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());


来源:https://stackoverflow.com/questions/6136435/how-to-create-htmlunit-htmlpage-object-from-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!