我用HtmlUnit上GOOGLE

来源:互联网 发布:c语言求最大公倍数 编辑:程序博客网 时间:2024/06/10 13:01

巧用HtmlUnit

首先加入HTMLUNITJAR FILEdownload from http://htmlunit.sourceforge.net ,现在好象支持到了1.11 version,另外还须junit.jarsee below:

新建TEST文件夹存放测试类

import java.io.IOException;

import java.net.MalformedURLException;

import java.net.URL;

import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;

import com.gargoylesoftware.htmlunit.WebClient;

import com.gargoylesoftware.htmlunit.html.HtmlForm;

import com.gargoylesoftware.htmlunit.html.HtmlPage;

import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput;

import com.gargoylesoftware.htmlunit.html.HtmlTextInput;

import junit.framework.TestCase;

 

public class Tests extends TestCase {

    public void testlist() throws FailingHttpStatusCodeException, IOException {

       WebClient client=new WebClient();

       URL url= new URL("http://www.google.com");

       HtmlPage page=(HtmlPage) client.getPage(url);

       HtmlForm form = page.getFormByName("f");

       HtmlTextInput input= (HtmlTextInput)form.getInputByName("q");

       input.setValueAttribute("james");

HtmlSubmitInput ok=(HtmlSubmitInput)form.getInputByName("btnG");

       ok.click();

    }

}

类必须继承TestCasethis class is  in the package junit.framework,it is provided by junit.jar.

WebClient client=new WebClient();  creaete a web client,It’s simulating  a web browser. client它相当于虚拟一个浏览器。

URL url= new URL("http://www.google.com"); create a URL to access your application.

HtmlPage page=(HtmlPage) client.getPage(url); 这时相当于打开了一个谷歌的页面。

HtmlForm form = page.getFormByName("f");

       HtmlTextInput input= (HtmlTextInput)form.getInputByName("q");

       input.setValueAttribute("james");

HtmlSubmitInput ok=(HtmlSubmitInput)form.getInputByName("btnG");

       ok.click();

后面几句稍微有点基础的人应该知道我在GOOGLE的表单里写了一个字符串“james”然后点击了搜索按钮。

RUN as junit test.以上的操作将真的在页面中执行,这跟JUNIT是不同的,JUNIT只是模拟一个环境进行操作,比如在一个方法里写了更改数据库的操作,运行后,数据库是不会有的变动的。

 

我试图改变URL地址,刷自己的BLOG,但是失败了

错误500 ,好象是http://blog.csdn.net/scripts/jsframework.js 有段JS进行了控制。

 
原创粉丝点击