关于httpunit的信息
HttpUnit抓取Ajax网页,例子是去哪儿机票
先看效果实现原理发送请求 :将输入的目标网址及保存路径名称采用AJAX异步的方式发送到image.info.php文件,该文件中包含有一个ImageCatch类,注意:因为有一个是指定目标图片抓取,一个是只要指定一个网址,如形式,所以还要有一个参数用来判断是指定目标抓取还是指定网站抓取。接收请求 :接收发送过来的两个参数,目标网址及保存路径,实例化ImageCatch类,将地址及保存路径传进去,用file_get_contents函数将目标地址的内容读取赋值给一个变量$content。先说指定图片抓取的实现 :指定图片抓取的方法实现比较简单,直接用file_get_contents函数将图片读取到,再用file_put_contents写入到一个文件保存起来就可以了。指定网址抓取图片的实现方法跟指定图片地址抓取就有点不一样了,因为采用的是jquery+ajax无刷新模式抓取,所以,请求要一次一次发,先说第一次发什么请求,很显然,第一次发的请求内容是获取目标网址的所有图片地址及图片总数,那要怎样获取目标网址的所有图片地址呢?思路跟上面的一样,但方法不同;第一步:用file_get_contents函数读取目标网址赋值给一个content变量。第二步:用正则匹配所有img标签里的src属性,并保存在一个数组,这样网页的图片地址就已经拿到了第三步:用正则匹配所有样式表文件link标签的href属性,并保存在一个数组$arr1第四步:还是用file_get_contents函数读取获取的样式表文件,再用正则去匹配到css样式里的url背景图片地址,并保存在一个数组$arr2,这样css样式的图片又拿到了第五步:将$arr1和$arr2用array_merge函数进行合并成$arr,再用一个数组$arr3(‘total’=count($arr))得出图片总数并追加到数组$arr里面去,这样图片地址和总数都拿到了第六步:用json_encode编译一个返回json数据 第七步:接收返回回来的json数据,将数据都存入一个数组,判断是否数组为空,不为空,则用函数递归的方法调用一个函数,每调用一次,在返回结果后就将该数组的第一个元素去掉,再判断数组是否为空,不为空,则继续发送抓取请求,直到数组为空,全部图片就已经都抓取完毕。好了现在看例子index.php代码如下 !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "/TR/xhtml1/DTD/xhtml1-transitional.dtd"html xmlns="/1999/xhtml"headmeta http-equiv="Content-Type" content="text/html; charset=utf-8" /titlePHP远程图片抓取/titlestylebody { margin:0; padding:0; }#content { width:90%; height:auto; margin:0 auto; margin-top:20px; font-size:12px; color:#333; }#content .h1 { width:100%; line-height:30px; text-align:left; }#content .h2 { width:100%; line-height:30px; text-align:left; }#content .Schedule { width:auto; height:12px; margin:15px 0px; display:none; background:url() }#content ul { width:100%; height:auto; margin-top:10px; }#content ul li { height:24px; line-height:24px;}#content font { color:#f00; }/stylescript type="text/javascript" src="js/jquery.js"/scriptscript$(document).ready(function() {var TargetUrl;var Save;function error(info) {$('#content .h2 font').text(info);}function statusInfo(info) {$('#content ul').append('li'+info+'/li');}//禁用按钮function start_d() {$('#Single,#more').attr('disabled','disabled');}//解放按钮function start_s() {$('#Single,#more').removeProp('disabled');}//进度跳转function href() {location.href='#bottom';}//单个图片抓取$('#content .h1 #Single').click(function() {TargetUrl=$('#content .h2 .TargetUrl').val();Save=$('#content .h2 .Save').val();if (TargetUrl=='') {error(' * 请填写目标网址');return;}if (Save=='') {error(' * 请填写保存目录');return;}var zurl=new Array(TargetUrl);start_d();Crawl(zurl,Save);});function Crawl(zurl,Save) {start_d();$('#content .Schedule').show();if (zurl.length0) {var curl=zurl[0];$.ajax({url:'image.info.php?Single=Single',dataType:'json',type:'POST',data:'TargetUrl='+curl+'Save='+Save,success: function(data) {if (data.status=='ok') {statusInfo('远程图片 font'+curl+'/font 抓取成功 已保存在 font'+data.FileSave+'/font 文件大小:font'+data.FileSize+'/font');zurl.shift(); //删除第一个数组元素并返回Crawl(zurl,Save); //使用函数递归href();}else {zurl.shift(); //删除第一个数组元素并返回Crawl(zurl,Save); //使用函数递归statusInfo(data.status); //显示失败信息$('#content .Schedule').hide(); //隐藏LOADING图片start_s(); //按钮启用href();}}});}else {$('#content .Schedule').hide();statusInfo('图片抓取完毕');start_s();href();}}//多个图片抓取$('#content .h1 #more').click(function() {TargetUrl=$('#content .h2 .TargetUrl').val();Save=$('#content .h2 .Save').val();if (TargetUrl=='') {error(' * 请填写目标网址');return;}var str=/^(https?://)?([da-z.-]+).([a-z.]{2,6})([/w .-]*)*/?$/;if (!str.test(TargetUrl)) {error(' * 目标网址不正确');return;}if (Save=='') {error(' * 请填写保存目录');return;}start_d();$('#content .Schedule').show();$.ajax({url:'image.info.php?more=more',dataType:'json',type:'POST',data:'TargetUrl='+TargetUrl+'Save='+Save,success: function(data) {if (data[0]!='no') {statusInfo('在目标网址 font'+TargetUrl+'/font 找到 font'+data['total']+'/font 张图片,现正在进行抓取....');var zurl=new Array();for (i=0; idata['total']; i++) {zurl.push(data[i]);}Crawl(zurl,Save);}else {statusInfo("未抓取找到任何图片");$('#content .Schedule').hide();start_s();}}});});$('#clear').click(function() {$('#content ul li').remove();});});/script/headbodydiv id="content"h1PHP远程图片抓取程序/h1div class="h1"指定图片抓取:input type="button" value=" 开始抓取 " id="Single" / font目标网址如:;/font指定网址抓取:input type="button" value=" 开始抓取 " id="more" / font目标网址如:;/fontinput type="button" value=" 清空状态信息 " id="clear" //divdiv class="Schedule"font正在抓取,请稍后.../font img src="loading.gif" border="0" //divdiv class="h2"目标网址:input type="text" class="TargetUrl" size="40" / 保存地址:input type="text" class="Save" /font/font/divul/ula name="bottom"/a/div/body/html images.info.php代码如下 ?phpheader('Content-Type; text/json; charset=utf-8');$Single=$_GET['Single'];$more=$_GET['more'];$TargetUrl=$_POST['TargetUrl'];$Save=$_POST['Save'];//判断是抓取单个图片还是多个图片if ($Single=='Single') {$ImageCatch=new ImageCatch($TargetUrl,$Save);$ImageCatch-S();}else if ($more=='more') {$ImageCatch=new ImageCatch($TargetUrl,$Save);$ImageCatch-M();}//图片抓取类class ImageCatch {private $TargetUrl; //目标地址private $Save; //保存地址private $FileName; //文件名称及路径private $Type; //文件类型private $Size; //文件大小//构造函数public function __construct($TargetUrl,$Save) {$this-TargetUrl=str_replace("'",'',$TargetUrl); //去掉单引号$this-Save=$Save;}//CSS样式表中图片抓取方法public function CSS() {$content=@file_get_contents($this-TargetUrl);//CSS图片过滤preg_match_all('/link.+href="?(.*?.css)"?.+/i',$content,$css);$css[1]=array_unique($css[1]);//移除重复的值$match2=array();if (count($css[1])0) {foreach($css[1] as $val) {if (!preg_match('/^(https?://)/i',$val)) {$val=$this-TargetUrl.'/'.$val;$csscontent=@file_get_contents($val);}else {$csscontent=@file_get_contents($val);}//匹配图片URL地址preg_match_all('/url((.*))/i',$csscontent,$cssimg);$cssimg[1]=array_unique($cssimg[1]);//移除重复的值} foreach($cssimg[1] as $val) {//去除 " ) 字符$val=preg_replace(array('/")/'),'',$val);//去除../字符$val=str_replace('../','',$val);//检查是否是开头,如果不是则加上要抓取的网址if (!preg_match('/^(https?://)/i',$val)) {array_push($match2,$this-TargetUrl.'/'.$val);}else {array_push($match2,$val);}}return $match2;}}//计算并返回图片数量及地址public function M() {$content=@file_get_contents($this-TargetUrl);//网页图片过滤$str='/img.+src="?(.+.(jpggifbmpbnppng))"?.+/i';preg_match_all($str,$content,$res);if ($res[1]) {$res[1]=array_unique($res[1]);//移除重复的值$httpstr='/^(https?://)/i';$match=array();foreach($res[1] as $val) {if (!preg_match($httpstr,$val)) {array_push($match,$this-TargetUrl.'/'.$val);}else {array_push($match,$val);}}$cssimg=$this-CSS();//扫描出css文件图片的总数与网页图片相加得到总数$total=array("total"=count($match)+count($cssimg));$result=array_merge($total,$match,$cssimg);//返回JSON数据echo json_encode($result);}else {$res=array('no');echo json_encode($res);}exit;}//抓取并保存图片public function S() {$this-Type=substr(strrchr($this-TargetUrl,'.'),1);$this-FileName=$this-Save.'/'.substr(strrchr($this-TargetUrl,'/'),1);$this-imageType();$content=@file_get_contents($this-TargetUrl);$this-imageDir();if (!@file_put_contents($this-FileName,$content,FILE_USE_INCLUDE_PATH)) {@unlink($this-FileName);exit('{"status":"没有找到 '.$this-TargetUrl.' 图片"}');}else {$this-imageSize();exit('{"status":"ok","FileSave":"'.$this-FileName.'","FileSize":"'.$this-Size.'"}');}}//新建目录private function imageDir() {if (!@file_exists($this-Save)) {if (!@mkdir($this-Save,0700)) {exit('{"status":"新建保存目录失败"}');}}}//文件类型判断private function imageType() {$typeArr=array('jpg','png','gif','zip','rar');if (!in_array($this-Type,$typeArr)) {exit('{"status":"要执行抓取的文件扩展名有错误,'.$this-TargetUrl.'"}');}}//文件大小检测private function imageSize() {if (file_exists($this-FileName)) {$this-Size=filesize($this-FileName);if ($this-Size1024*1024*1024) {$this-Size=round($this-Size/1024/1024/1024,2).' GB';}else if ($this-Size1024*1024) {$this-Size=round($this-Size/1024/1024,2).' MB';}else if ($this-Size1024) {$this-Size=$this-Size/1024;$this-Size=ceil($this-Size).'KB';}else {$this-Size=$this-Size.'bit';}}else {return '未找到文件';}}}?
如何使用HttpUnit进行集成测试
HttpUnit是一个集成测试工具,主要关注Web应用的测试,提供的帮助类让测试者可以通过Java类和服务器进行交互,并且将服务器端的响应当作文本或者DOM对象进行处理。HttpUnit还提供了一个模拟Servlet容器,让你可以不需要发布Servlet,就可以对Servlet的内部代码进行测试。本文中作者将详细的介绍如何使用HttpUnit提供的类完成集成测试。
httpunit新手入门怎么用于eclipse
import java.io.IOException;
import java.net.MalformedURLException;
import org.xml.sax.SAXException;
import com.meterware.httpunit.GetMethodWebRequest;
import com.meterware.httpunit.HttpUnitOptions;
import com.meterware.httpunit.PostMethodWebRequest;
import com.meterware.httpunit.WebConversation;
import com.meterware.httpunit.WebForm;
import com.meterware.httpunit.WebLink;
import com.meterware.httpunit.WebRequest;
import com.meterware.httpunit.WebResponse;
public class HttpunitTest {
public static void main(String[] args) {
try {
//HttpunitTest.testGetHtmlContent();
//HttpunitTest.testGetMethod();
//HttpunitTest.testPostMethod();
HttpunitTest.testFormSubmit();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void testGetHtmlContent() throws IOException, SAXException{
System.out.println("直接获取网页内容:");
HttpUnitOptions.setScriptingEnabled(false);
// 建立一个WebConversation实例
WebConversation wc = new WebConversation();
// 向指定的URL发出请求,获取响应
WebResponse wr = wc.getResponse("");
// 用getText方法获取相应的全部内容
// 用System.out.println将获取的内容打印在控制台上
System.out.println(wr.getText());
}
/**
* 用get方法获取页面内容
* @throws MalformedURLException
* @throws IOException
* @throws SAXException
*/
public static void testGetMethod() throws MalformedURLException,
IOException, SAXException {
System.out.println("向服务器发送数据,然后获取网页内容:");
// 建立一个WebConversation实例
WebConversation wc = new WebConversation();
// 向指定的URL发出请求
WebRequest req = new GetMethodWebRequest("");
// 给请求加上参数
req.setParameter("query", "四氯化碳");
// 获取响应对象
WebResponse resp = wc.getResponse(req);
// 用getText方法获取相应的全部内容
// 用System.out.println将获取的内容打印在控制台上
System.out.println(resp.getText());
}
/**
* 用post方法获取页面内容
* @throws MalformedURLException
* @throws IOException
* @throws SAXException
*/
public static void testPostMethod() throws MalformedURLException,
IOException, SAXException {
System.out.println("使用Post方式向服务器发送数据,然后获取网页内容:");
// 建立一个WebConversation实例
WebConversation wc = new WebConversation();
// 向指定的URL发出请求
WebRequest req = new PostMethodWebRequest("");
// 给请求加上参数
req.setParameter("user_name", "test");
req.setParameter("password", "111111");
// 获取响应对象
WebResponse resp = wc.getResponse(req);
// 用getText方法获取相应的全部内容
// 用System.out.println将获取的内容打印在控制台上
System.out.println(resp.getText());
}
/**
* 获取页面链接并模拟点击
* @throws MalformedURLException
* @throws IOException
* @throws SAXException
*/
public static void testClickLink() throws MalformedURLException,
IOException, SAXException {
System.out.println("获取页面中链接指向页面的内容:");
// 建立一个WebConversation实例
WebConversation wc = new WebConversation();
// 获取响应对象
WebResponse resp = wc.getResponse("");
// 获得页面链接对象
WebLink link = resp.getLinkWith("百度");
// 模拟用户单击事件
link.click();
// 获得当前的响应对象
WebResponse nextLink = wc.getCurrentPage();
// 用getText方法获取相应的全部内容
// 用System.out.println将获取的内容打印在控制台上
System.out.println(nextLink.getText());
}
/**
* 测试WebForm的处理表单和提交能力
*/
public static void testFormSubmit(){
HttpUnitOptions.setScriptingEnabled(false);
WebConversation wc = new WebConversation();
WebRequest request = new PostMethodWebRequest("");
WebResponse response = null;
try {
response = wc.getResponse(request);
//获得Html中的form表单,HttpUnit将他封装成WebForm对象
WebForm form = response.getForms()[0];
//WebForm对象提供getParameterValue的方法将根据表单中的name获得对应的value,而不用管该元素的类型。
//对表单进行处理操作
form.setParameter("username", "le");
form.setParameter("password", "le");
//提交表单 获得新的response
response = form.submit();
System.out.println(response.getText());
System.out.println("----------------------------");
// 获得页面链接对象
WebLink link = response.getLinkWith("新闻中心");
//模拟用户单击事件
link.click();
// 获得当前的响应对象
WebResponse nextLink = wc.getCurrentPage();
// 用getText方法获取相应的全部内容
// 用System.out.println将获取的内容打印在控制台上
System.out.println(nextLink.getText());
} catch (IOException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
}
}
常用语句:
initialPage.getLinkWithID( "go" ).click();
wc.getResponse( getHostPath() + "/TextPage.txt" ).getReceivedPage().getTitle();
structuredPage.getDOM()
wc.getClientProperties().setOverrideContextType( "text/html" );
simplePage.getTitle() );
simplePage.getCharacterSet()
new GetMethodWebRequest( "file:" + file.getAbsolutePath() )
addResourceHeader( "SimplePage.html", "Refresh: 2;URL=NextPage.html" );
wc.getClientProperties().setAutoRefresh( true );
simplePage.getMetaTagContent("name","robots"));
simplePage.getMetaTagContent("name","keywords"));
simplePage.getMetaTagContent("http-equiv","Expires")
simplePage.getExternalStyleSheet()
simplePage.getElementWithID( "aForm" )
simplePage.getElementsWithName( "aForm" )
simplePage.getElementsWithAttribute( "class", "first" )
wc.getResponse("/NoLinks.html" ).getLinks()
simplePage.getLinkWith( "no link" )
getLinkWithImageText( "Next --" )
HttpUnitOptions.setImagesTreatedAsAltText( true );
simplePage.getLinkWith( "Next --" )
simplePage.getFirstMatchingLink( WebLink.MATCH_URL_STRING, "/other.html" )
simplePage.getLinkWithName( "nextLink" )
simplePage.getElementWithID( "activeID" )
initialPage.getLinkWithImageText("Blah Blah")
nextPage.getTitle()
link.click()
link.getTarget() ).getTitle()
wc.getResponse( link.getRequest() )
request.getRequestParameterNames()
HttpUnitOptions.setLoggingHttpHeaders(false);
HttpUnitOptions.setScriptingEnabled( false );
simplePage.getImages()
WebImage image = simplePage.getImageWithAltText( "one" )
simplePage.getImageWithSource( "junk.png" )
link.getURLString()
imageRequest.getURL().toExternalForm()
wc.getFrameNames()
wc.getFrameContents( "_top" )
e.getResponseCode()
e.getResponseMessage()
response.getText()
response.getContentType()
wc.getCookieValue( "name" )
wc.getCookieNames()
wc.getCookieDetails("age")
wc.putCookie( "EMPTYVALUE", "non-empty" );
wc.getClientProperties().setUserAgent( "me alone" );
wc.setHeaderField( "junky", "Mozilla 6" );
wc.setAuthorization( "user", "password" );
wc.setProxyServer( "localhost", getHostPort(), "user", "password" );
WebForm form = wr.getFormWithID( "main" );
form.setParameter( "name", "master" );
form.submit();
SubmitButton button = form.getSubmitButton( "save", button.click()
page.getFormWithID( "form" ).getSubmitButton( "update" )
page.getFormWithName( "nobody" )
form.getParameterNames()
form.hasParameterNamed( "third" )
form.getParameterValue( "name" )
WebForm form = _wc.getResponse( getHostPath() + "/OneForm.html" ).getForms()[0];
WebRequest request = form.getRequest();
request.setParameter( "name", "master" );
form.reset()
response.getTextBlocks() 获取段落
BlockElement paragraph = response.getTextBlocks()[1];
paragraph.getLinks()
paragraph.getLinkWithID( "httpunit" )
response.getTextBlocks()[0].getLinkWithID( "httpunit" )
paragraph.getFirstMatchingLink( WebLink.MATCH_CONTAINED_TEXT, "home page" )
paragraph.getLinkWithID( "httpunit" ).getRequest().getURL().toExternalForm()
request.getURL().toExternalForm()
table.getRowCount()
table.getColumnCount()
table.getCellAsText( 2, 0 )
page.getTableWithID("table")
table.getTableCellWithID("id2")
form.getMethod()
form.getAction()
form.getScriptableObject().setAction( "/tell" )
form.getSubmitButtons()
form.getButtonWithID("doit")
httpUnit结合jsoup如何获得javascript执行完后的最终html
楼主是要做抓取吗?据我所知是不行的,如果只是获取的话,JS执行完了可以用jq的html取出来
httpunit模拟URL以HTTPS开头的响应问题
https以保密为目标研发,其安全基础是SSL协议。而SSL的工作方式
客户端要收发几个握手信号:
发送一个ClientHello消息,说明它支持的密码算法列表、压缩方法及最高协议版本,也发送稍后将被使用的随机数。
然后收到一个ServerHello消息,包含服务器选择的连接参数,源自客户端初期所提供的ClientHello。
当双方知道了连接参数,客户端与服务器交换证书(依靠被选择的公钥系统)。这些证书通常基于X.509,不过已有草案支持以OpenPGP为基础的证书。
服务器请求客户端公钥。客户端有证书即双向身份认证,没证书时随机生成公钥。
客户端与服务器通过公钥保密协商共同的主私钥(双方随机协商),这通过精心谨慎设计的伪随机数功能实现。结果可能使用Diffie-Hellman交换,或简化的公钥加密,双方各自用私钥解密。所有其他关键数据的加密均使用这个「主密钥」。
注意客户端和服务器端要交换证书。或者提供公钥。java中由Java 安全套接口扩展来实现,即Java Secure Socket Extension, JSSE,jdk中提供了 keytool这个工具,允许管理员管理公共/专用密钥对和关联证书。还允许用户高速缓存正与其通信的另一方的公共密钥(以证书形式)。
补充~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
原理性的东西都跟你说了,你自己就不能去找找了?什么东西都要被人给你找出来,你自己不能找一下吗,这样才是学习~~
好吧,具体步骤看这里
不要说看不懂英文。
httpunit是哪个公司的产品?
不算是产品吧,它是一个开源的测试工具,是SourceForge下面的一个开源项目,基于JUnit的一个测试框架。