HTMLUnit打开窗口显示google.com

时间:2010-12-12 12:00:51

标签: htmlunit

我需要一些非常简单的帮助才能在Java桌面应用程序的浏览器中打开google.com。

使用HTMLUnit和类似的东西:

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;

公共类HTMLUnit {

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

//创建并初始化WebClient对象      WebClient webClient = new WebClient(BrowserVersion.INTERNET_EXPLORER_8);

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

public void handleRefresh(Page page,URL url,int arg)抛出IOException {     的System.out.println( “handleRefresh”);    }

 });

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

在NetBeans中运行此文件时,我应该弹出一个窗口吗?

3 个答案:

答案 0 :(得分:2)

没有

HtmlUnit是一个“无头浏览器”。这意味着您使用HtmlUnit执行的所有操作都不可见。

相反,我建议您尝试使用WebDriver / Selenium 2(http://seleniumhq.org/docs/09_webdriver.html)。使用WebDriver,您可以远程控制Firefox或IE等浏览器。

类似的东西:

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");

     }
}

答案 1 :(得分:1)

...这可能与请求中发送的参数有关。我比较了HTMLUnit和原始浏览器发送的那些。有区别。顺便说一句,您可以在HmlUnit中添加缺少的请求参数。

答案 2 :(得分:0)

有趣的是,这段代码有效,我改用了IE浏览器,看起来FireFox已经出现了问题。

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.ie.InternetExplorerDriver;



public class KeywordTool {
    private static final By By = null;

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

        // Go to the Google Suggest home page
        driver.get("http://www.google.com");

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

     }
}