【问题标题】:How to create HtmlUnit HTMLPage object from String?如何从字符串创建 HtmlUnit HTMLPage 对象?
【发布时间】:2020-07-08 00:26:09
【问题描述】:

这个question was asked once already,但我猜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());

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

有人知道怎么做吗?在我看来这很奇怪,它不能轻易完成。

【问题讨论】:

    标签: java htmlunit


    【解决方案1】:

    此代码适用于 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());
    

    【讨论】:

    • 我不知道你在看什么,但构造函数是受保护的。类在 java 中必须是“公共的”,除非它是内部类或嵌套类...
    • 糟糕,我正在查看类声明,Groovy/Java 的微妙之处使我的代码在 GroovyConsole 中工作。我已经进行了相应的编辑,并进行了简单的修改。现在应该对你有用
    • 在 Groovy 中,由于语言的动态特性,受保护的和私有的方法被视为公开的......这是known bug,但我有时很容易忘记它;-)
    【解决方案2】:

    使用 HTMLUnit 2.40,Grooveek 的代码将无法编译,您会得到“无法对 HTMLParser 类型的非静态方法 parseHtml(WebResponse, WebWindow) 进行静态引用”。但是现在有一个类 HtmlUnitNekoHtmlParser 实现了 HTMLParser 接口,所以下面的代码可以工作:

    StringWebResponse response = new StringWebResponse(
        "<html><head><title>Test</title></head><body></body></html>", 
        new URL("http://www.example.com"));
    HtmlPage page = new HtmlUnitNekoHtmlParser().parseHtml(
        response, new WebClient().getCurrentWindow());
    

    【讨论】:

    • .parseHtml(...) 自 HtmlUnit 2.43.0 起不再可用
    猜你喜欢
    • 1970-01-01
    • 2011-09-23
    • 1970-01-01
    • 2015-09-08
    • 2012-04-14
    • 1970-01-01
    • 1970-01-01
    • 2015-08-19
    相关资源
    最近更新 更多