Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTMLUnit Open Window showing google.com

Tags:

htmlunit

I need some very simple help to open google.com in a browser from a Java desktop app.

Looking at using HTMLUnit and something like this:

import java.io.IOException;

import java.net.URL; import java.util.List; import com.gargoylesoftware.htmlunit.WebWindow; import com.gargoylesoftware.htmlunit.BrowserVersion; import com.gargoylesoftware.htmlunit.Page; import com.gargoylesoftware.htmlunit.RefreshHandler; import com.gargoylesoftware.htmlunit.WebClient; import com.gargoylesoftware.htmlunit.html.HtmlAnchor; import com.gargoylesoftware.htmlunit.html.HtmlForm; import com.gargoylesoftware.htmlunit.html.HtmlPage; import com.gargoylesoftware.htmlunit.html.HtmlTable; import com.gargoylesoftware.htmlunit.html.HtmlTableRow;

public class HTMLUnit {

public static void main(String[] args) throws Exception {

// Create and initialize WebClient object WebClient webClient = new WebClient(BrowserVersion.INTERNET_EXPLORER_8);

        webClient.setThrowExceptionOnScriptError(false);
 webClient.setRefreshHandler(new RefreshHandler() {

public void handleRefresh(Page page, URL url, int arg) throws IOException { System.out.println("handleRefresh"); }

 });

        Page NewGooglePage = webClient.openWindow(new URL("http://www.google.com"), "GoogleWindow").getEnclosedPage();

When running this file in NetBeans should I get a window to pop?

like image 984
Doug Stewart Avatar asked Jul 17 '26 12:07

Doug Stewart


2 Answers

No,

HtmlUnit is a "headless browser". It means every things you do with HtmlUnit are not visible.

Instead I suggest you try WebDriver/Selenium 2 (http://seleniumhq.org/docs/09_webdriver.html). With WebDriver you can remote control browser like Firefox or IE.

Something like:

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.RenderedWebElement;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class GoogleSuggest {
    public static void main(String[] args) throws Exception {
        // The Firefox driver supports javascript
        WebDriver driver = new FirefoxDriver();

        // Go to the Google Suggest home page
        driver.get("http://www.google.com/webhp?complete=1&hl=en");

        // Enter the query string "Cheese"
        WebElement query = driver.findElement(By.name("q"));
        query.sendKeys("Cheese");

     }
}
like image 185
Julien H. - SonarSource Team Avatar answered Jul 19 '26 03:07

Julien H. - SonarSource Team


...this may be related to the parameters send in the request. I compared the ones send by HTMLUnit and the original browsers. There are differences. By the way you can add the missing request paramters in HmlUnit.

like image 20
RudeUrm Avatar answered Jul 19 '26 01:07

RudeUrm