以下代碼嘗試搜索谷歌,並將結果作爲文本或HTML返回。 該代碼幾乎完全從在線代碼片段中直接複製,並且我沒有理由不返回搜索結果。如何在沒有瀏覽器的情況下使用htmlunit提交搜索查詢來返回谷歌搜索結果?使用HtmlUnit來搜索谷歌
import com.gargoylesoftware.htmlunit.WebClient;
import java.io.*;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlInput;
import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput;
import java.net.*;
public class GoogleSearch {
public static void main(String[] args)throws IOException, MalformedURLException
{
final WebClient webClient = new WebClient();
HtmlPage page1 = webClient.getPage("http://www.google.com");
HtmlInput input1 = page1.getElementByName("q");
input1.setValueAttribute("yarn");
HtmlSubmitInput submit1 = page1.getElementByName("btnK");
page1=submit1.click();
System.out.println(page1.asXml());
webClient.closeAllWindows();
}
}
你也許可以告訴我們程序的功能。我們知道它應該做什麼,但不知道它做了什麼。有什麼異常?堆棧跟蹤? –
它運行,生成很好,沒有例外,但不打印出XML/HTML。 btnG工作,並不確定爲什麼firefox看到btnK應該有一個btnG。它也可能是解析器的主要部分。 –