发布于 2015-09-01 14:56:20 | 329 次阅读 | 评论: 0 | 来源: 网友投递

这里有新鲜出炉的PhantomJS教程,程序狗速度看过来!

PhantomJS

PhantomJS 是一个基于WebKit的服务器端 JavaScript API。它全面支持web而不需浏览器支持,其快速,原生支持各种Web标准: DOM 处理, CSS 选择器, JSON, Canvas, 和 SVG。PhantomJS可以用于页面自动化,网络监测,网页截屏,以及无界面测试等。


phantomjs表单提交,其实就是对DOM就行操作(获取元素),在这里实现了动态传入各种参数

不说了 直接上代码

var page = require(‘webpage‘).create(),
system = require(‘system‘),fname;                                   
 
var hostUrl = system.args[1];
var resId = system.args[2];
var fileName = system.args[3];
console.log("访问地址:"+hostUrl);
console.log("资源名称:"+resId);
console.log("资源路径:"+fileName);
console.log(‘请稍等,正在提交数据。。。‘);

page.open(hostUrl, function (stat) {
    page.uploadFile(‘input[name=resFile]‘, fileName);
    page.evaluate(function (resId) {
        document.querySelector(‘input[name=resId]‘).value = resId;
        document.querySelector(‘input[name=resConf]‘).value = ‘{"resVer":"‘+new Date().getTime()+‘"}‘;
        document.querySelector(‘form‘).submit();
    },resId);
    phantom.exit();
});

这里会出现一个问题,如果上传的资源文件过大,时间过长,就会出现上传失败

所以在这里要通过一个状态来判断是否上传完成,onResourceReceived资源收到后调用后方法

var page = require(‘webpage‘).create(),
system = require(‘system‘),fname;                                   
 
var hostUrl = system.args[1];
var resId = system.args[2];
var fileName = system.args[3];
console.log("访问地址:"+hostUrl);
console.log("资源名称:"+resId);
console.log("资源路径:"+fileName);
console.log(‘请稍等,正在提交数据。。。‘);

page.open(hostUrl, function (stat) {
    page.uploadFile(‘input[name=resFile]‘, fileName);
    page.evaluate(function (resId) {
        document.querySelector(‘input[name=resId]‘).value = resId;
        document.querySelector(‘input[name=resConf]‘).value = ‘{"resVer":"‘+new Date().getTime()+‘"}‘;
        document.querySelector(‘form‘).submit();
    },resId);
});
page.onResourceReceived = function(response) {
     if(response.stage==‘end‘ && response.url.indexOf(‘.json‘)>-1){
        phantom.exit();
     }
};

这里判断了stage状态结束,还有当前地址改变,完成了上传,就能结束当前操作

通过phantomjs实现了前端不能实现的,在测试中效果很明显



最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务