Search code examples
htmlunit

Use HtmlUnit to search google


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();
      }
    } 

Solution

  • There must be some browser detection that changes the generated HTML, because when inspecting the HTML with page1.getWebResponse().getContentAsString(), the submit button is named btnG and not btnK (which is not what I observe in Firefox). Make this change, and the result will be the expected one.