如何从String创建HtmlUnit HTMLPage对象? [英] How to create HtmlUnit HTMLPage object from String?

查看:117
本文介绍了如何从String创建HtmlUnit HTMLPage对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题已经被问过了,但我猜测API已经改变,答案已经无效了。

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());

无法完成,因为TopLevelWindow受到保护,因为扩展/实现窗口之类的东西是因为荒谬:)

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.

推荐答案

此代码适用于GroovyConsole

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());

这篇关于如何从String创建HtmlUnit HTMLPage对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆