使用 HtmlUnit 搜索 google
以下代码尝试搜索 google,并以文本或 html 形式返回结果。 该代码几乎完全是直接从在线代码片段中复制的,我认为它没有理由不返回搜索结果。如何在没有浏览器的情况下使用 htmlunit 提交搜索查询来返回 google 搜索结果?
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();
}
}
The following code is an attempt to search google, and return the results as text or html.
The code was almost entirely copied directly from code snippets online, and i see no reason for it to not return results from the search. How do you return google search results, using htmlunit to submit the search query, without a browser?
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();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
必须有一些浏览器检测会更改生成的 HTML,因为使用
page1.getWebResponse().getContentAsString()
检查 HTML 时,提交按钮名为btnG
而不是btnK
(这不是我在 Firefox 中观察到的情况)。进行这一更改,结果将是预期的。There must be some browser detection that changes the generated HTML, because when inspecting the HTML with
page1.getWebResponse().getContentAsString()
, the submit button is namedbtnG
and notbtnK
(which is not what I observe in Firefox). Make this change, and the result will be the expected one.我刚刚检查过这个。它实际上是 2 个 google 页面的 2 个 id:
I've just checked this. It's actually 2 ids for 2 google pages: