標籤:
phantomjs表單提交,其實就是對DOM就行操作(擷取元素),在這裡實現了動態傳入各種參數
不說了 直接上代碼
1 var page = require(‘webpage‘).create(), 2 system = require(‘system‘),fname; 3 4 var hostUrl = system.args[1]; 5 var resId = system.args[2]; 6 var fileName = system.args[3]; 7 console.log("訪問地址:"+hostUrl); 8 console.log("資源名稱:"+resId); 9 console.log("資源路徑:"+fileName);10 console.log(‘請稍等,正在提交資料。。。‘);11 12 page.open(hostUrl, function (stat) {13 page.uploadFile(‘input[name=resFile]‘, fileName);14 page.evaluate(function (resId) {15 document.querySelector(‘input[name=resId]‘).value = resId;16 document.querySelector(‘input[name=resConf]‘).value = ‘{"resVer":"‘+new Date().getTime()+‘"}‘;17 document.querySelector(‘form‘).submit();18 },resId);19 phantom.exit();20 });
這裡會出現一個問題,如果上傳的資源檔過大,時間過長,就會出現上傳失敗
所以在這裡要通過一個狀態來判斷是否上傳完成,onResourceReceived資源收到後調用後方法
1 var page = require(‘webpage‘).create(), 2 system = require(‘system‘),fname; 3 4 var hostUrl = system.args[1]; 5 var resId = system.args[2]; 6 var fileName = system.args[3]; 7 console.log("訪問地址:"+hostUrl); 8 console.log("資源名稱:"+resId); 9 console.log("資源路徑:"+fileName);10 console.log(‘請稍等,正在提交資料。。。‘);11 12 page.open(hostUrl, function (stat) {13 page.uploadFile(‘input[name=resFile]‘, fileName);14 page.evaluate(function (resId) {15 document.querySelector(‘input[name=resId]‘).value = resId;16 document.querySelector(‘input[name=resConf]‘).value = ‘{"resVer":"‘+new Date().getTime()+‘"}‘;17 document.querySelector(‘form‘).submit();18 },resId);19 });20 page.onResourceReceived = function(response) {21 if(response.stage==‘end‘ && response.url.indexOf(‘.json‘)>-1){22 phantom.exit();23 }24 };
這裡判斷了stage狀態結束,還有當前地址改變,完成了上傳,就能結束當前操作
通過phantomjs實現了前端不能實現的,在測試中效果很明顯
phantomjs form提交