How to create HtmlUnit HTMLPage object from String?

前端 未结 2 1875
耶瑟儿~
耶瑟儿~ 2020-12-30 01:40

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\");
String         


        
相关标签:
2条回答
  • 2020-12-30 02:03

    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());
    
    0 讨论(0)
  • 2020-12-30 02:05

    Using HTMLUnit 2.40, Grooveek's code won't compile, you get "Cannot make a static reference to the non-static method parseHtml(WebResponse, WebWindow) from the type HTMLParser". But there is now a class HtmlUnitNekoHtmlParser implementing the HTMLParser interface, so the following code works:

    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());
    
    0 讨论(0)
提交回复
热议问题