2011-05-26 51 views
17

question was asked once already,但我猜API改變了,答案是無效的。如何從String創建HtmlUnit HTMLPage對象?

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被保護之類的東西擴展/實現,因爲該窗口是可笑:)

任何人有一個想法如何做到這一點?在我看來,奇怪的是它不能輕易完成。

回答

23

這個代碼在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()); 
+1

,我不知道你在找什麼,但構造函數是受保護的。在Java中,類必須是「公共」的,除非它是內部類或嵌套類... – lisak 2011-05-26 11:19:35

+0

我的不好,我正在尋找Groovy/Java的類聲明和微妙使我的代碼在GroovyConsole中工作。我已經編輯了一個簡單的轉折。那現在應該適合你 – Grooveek 2011-05-26 12:55:16

+0

謝謝Grooveek,它是如何在Groovy控制檯中工作的? – lisak 2011-05-26 12:57:21