testapp.js(node.js+phantom.js)
var http = require('http');
var path = require('path');
var url = require('url');
var phantom = require("phantom");
var fs = require('fs');
http.createServer(function (req, res) {
var params = url.parse(req.url, true);
if(params.pathname=="/httpserv"){
if(params.query.mode=="testJson1"){ // /httpserv?mode=testJson1
console.log("testJson1");
res.setHeader("Pragma","no-cache");
res.setHeader("Expires","-1");
res.writeHead(200, {'Content-Type': 'text/javascript; charset="UTF-8"'});
var jdata='{"name":"山田太郎","sex":"男","age":"20"}';
var sdata="var data="+jdata;
res.end(sdata);
}
else if(params.query.mode=="testJson2"){ // /httpserv?mode=testJson2
console.log("testJson2");
res.setHeader("Pragma","no-cache");
res.setHeader("Expires","-1");
res.writeHead(200, {'Content-Type': 'text/javascript; charset="UTF-8"'});
var jdata='{"name":"山田太郎","sex":"男","age":"20"}';
var sdata=params.query.callback+"("+jdata+")";
res.end(sdata);
}
else if(params.query.mode=="testJson0"){ // /httpserv?mode=testJson0
console.log("testJson0");
res.setHeader("Pragma","no-cache");
res.setHeader("Expires","-1");
res.writeHead(200, {'Content-Type': 'text/javascript; charset="UTF-8"'});
var jdata='{"name":"山田太郎","sex":"男","age":"20"}';
res.end(jdata);
}
else if(params.query.mode=="getJson"){ // /httpserv?mode=getJson・・
console.log("getJson ");
var ps=params.query.url;
var options = url.parse(ps);
options.headers={'user-agent':'Mozilla/5.0(Windows NT 6.1) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.57 Safari/537.17'};
//プロキシ経由にも対応
var proxy="yes";
if(proxy=="yes"){
options.hostname="proxy2.is.fujimic.com";
options.port="8080";
options.path=ps;
}
//HTTPクライアントによるデータ収集
var request = http.request(options, function(res) {});
var body="";
request.end();
request.on('response', function (response) {
response.setEncoding('utf8');
response.on('data', function (chunk) {
body += chunk;
});
response.on('end', function () {
body=params.query.callback+"("+body+")";
console.log("body="+body);
res.setHeader("Pragma","no-cache");
res.setHeader("Expires","-1");
res.writeHead(200, {'Content-Type': 'text/javascript; charset="UTF-8"'});
res.end(body);
});
});
}
else if(params.query.mode=="mail"){ // /httpserv?mode=mail・・
console.log("mail");
var bid=params.query.bid;
var bpw=params.query.bpw;
var userid=params.query.id;
var pw=params.query.pw;
getMailData(bid,bpw,userid,pw,res);
}
}
//要求ファイル(HTMLや画像など)の送信
else{
var filePath = url.parse(req.url).pathname;
var fullPath = getRequestFilePath(filePath);
var ext = path.extname(fullPath);
console.log("fullPath="+fullPath+" ext="+ext);
path.exists(fullPath, function(exists) {
if(exists){
var contentType = MIME[ext.toLowerCase()];
if(contentType){
var statusCode = 200;
var body = fs.readFileSync(fullPath);
// Check HTTP Method
var method = req.method;
if (method == "GET" || method == "POST") {
res.setHeader("Pragma","no-cache");
res.setHeader("Expires","-1");
res.writeHead(statusCode, {
'Content-Type': contentType,
'Content-Length': body.length
});
res.write(body);
}
res.end();
}
}
});
}
// -----------------------------------------------------------
/*
Node.js × PhantomJS で何でもサクサクスクレイピングするよ!
http://d.hatena.ne.jp/hecomi/20130108/1357653054
ActiveMailへの接続
basic認証、ログイン、受信箱を開き、タイトルを表示する
PhantomJSはWebブラウザなしでJavaScriptの実行が可能なツールです。内部ではQtWebKitを使用しているため、単にJavaScriptを実行するだけではなく、DOMやCSSの取り扱いや、CanvasやSVGによる描画などにも対応しています。
getMailDataはライブラリとして外出ししたかったのですが、HttpResponseをコールバックで渡せなかったので、
Httpサーバーの中に組み込んだ(2013/4/4)。
*/
//exports.getMailData = function(bid,bpw,userid,pw,func){//getMailDataのモジュール化
function getMailData(bid,bpw,userid,pw,res){
var testindex=0, loadInProgress = false;
var title_list="";
//phantom.create("--proxy=http://proxy2.is.fujimic.com:8080", function(ph){
phantom.create(function(ph) {
ph.createPage(function(page) {
page.set("onLoadStarted", function() {
console.log("load Started");
loadInProgress = true;
});
page.set("onLoadFinished", function() {
console.log("load Finished");
loadInProgress = false;
});
//PhantomJSで順次実行する関数
var funcs=[
//ログイン画面の表示とBasic認証
function() {
console.log("ActiveMailサイトへのアクセス(Basic認証)");
//Basic認証情報のセット
page.set("settings.userName", bid);
page.set("settings.password", bpw);
//ユーザーエージェントのセット
page.set("settings.userAgent", "Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:13.0) Gecko/20100101 Firefox/13.0");
//画面サイズのセット
page.set("viewportSize", {width: 1024, height: 768});
//サイトのオープン
page.open("https://gm.fujimic.com/", function(status) {
console.log("status="+status);
if (status !== "success") {
testindex=funcs.length;
console.log("opened Page? ", status+" "+testindex);
ph.exit();
return;
}
});
},
//ログイン情報のセット
function() {
console.log("ログイン画面で、ユーザーID、PWの入力");
page.render("site1.jpg");
//console.log(userid+":"+pw);
page.evaluate(function(Userid,Pw) {
var arr=document.getElementsByTagName("input");
for (var i=0;i<arr.length;i++){
if(arr.item(i).getAttribute("type")=="text")arr.item(i).value=Userid;
else if(arr.item(i).getAttribute("type")=="password")arr.item(i).value=Pw;
}
},null,userid, pw);
},
//ログインボタンの押下
function() {
page.render("site3.jpg");
console.log("ログイン画面でのサブミット");
page.evaluate(function() {
var arr=document.getElementsByTagName("form");
for (var i=0;i<arr.length;i++){
if(arr.item(i).getAttribute("name")=="login"){
arr.item(i).submit();
break;
}
}
});
},
//ログイン後の画面表示と受信箱の押下
function() {
page.render("site4.jpg");
console.log("メール画面の表示と受信箱へのアクセス");
//メール受信
page.evaluate(function() {
amtop.changeContents('rmail');//受信箱のクリック
});
},
//受信箱の表示と受信データの取得
function() {
page.render("site5.jpg");
console.log("受信箱表示とメールタイトルの取得");
// iframe 内の HTML を取得
page.evaluate(function() {
var st='{"maildata":[';
var c=document.getElementById("contentIframe").contentWindow;
var arr=c.document.getElementsByTagName("tr");
for (var i=0;i<arr.length;i++){
var nd=arr.item(i);
if(nd.getAttribute("class")){
if(nd.getAttribute("class").indexOf("row")>0){
c=nd.childNodes;
if(c&&c.length==9){
/*
if(c.item(5)&&c.item(5).firstChild)st+=c.item(5).innerHTML+"\n";//title
if(c.item(6)&&c.item(6).firstChild)st+=c.item(6).innerHTML+"\n";//from
if(c.item(7)&&c.item(7).firstChild)st+=c.item(7).innerHTML+"\n";//date
*/
st+='{"title":"'+c.item(5).innerHTML+'","from":"'+c.item(6).innerHTML+'","date":"'+c.item(7).innerHTML+'"},';
}
}
}
}
st=st.substring(0,st.length-1)+"]}";
return st;
}, function(html) {
var s=html.split("@osaka@");
title_list = html;
});
},
//ログアウトボタンの押下
function() {
//Enter Credentials and send Login Info
console.log("ログアウトボタン押下");
page.evaluate(function() {
var nd=document.getElementById("header_button_logout");
nd.click();
});
},
//ログアウト画面の表示
function() {
console.log("ログアウト後の画面");
page.render("site7.jpg");
page.evaluate(function() {
return document.getElementsByTagName("html")[0].outerHTML;
}, function(html) {
//console.log(html);
ph.exit();
//response返信処理
if(res){
res.setHeader("Pragma","no-cache");
res.setHeader("Expires","-1");
/*
res.writeHead(200, {'Content-Type': 'text/html; charset="UTF-8"'});
res.end(title_list);
*/
res.writeHead(200, {'Content-Type': 'text/javascript; charset="UTF-8"'});
var sdata=params.query.callback+"("+title_list+")";
res.end(sdata);
}
dispList(title_list);
});
}
];
interval = setInterval(function() {
if (!loadInProgress && typeof funcs[testindex] == "function") {
console.log("step " + (testindex + 1));
funcs[testindex]();
testindex++;
}
if (typeof funcs[testindex] != "function") {
console.log("test complete! "+testindex);
clearInterval(interval);
return;
}
}, 2500);
function dispList(data){
console.log("titles=\n"+data);
}
});
});
}
// -----------------------------------------------------------
}).listen("8002", "127.0.0.1");
// Get Request File Path
var getRequestFilePath = function (filePath) {
//console.log("filePath="+filePath);
var fullPath = path.join(__dirname,path.join(".\/www", filePath));
return fullPath;
};
var MIME= {
".bmp" : "image\/bmp",
".css" : "text\/css",
".gif" : "image\/gif",
".htm" : "text\/html",
".html" : "text\/html",
".ico" : "image\/vnd.microsoft.icon",
".jpeg" : "image\/jpeg",
".jpg" : "image\/jpeg",
".js" : "text\/javascript;charset=utf-8",
".json" : "application\/json",
".jsonp" : "application\/json-p",
".lzh" : "application\/lha",
".pdf" : "application\/pdf",
".png" : "image\/png",
".txt" : "text\/plain;charset=utf-8",
".wav" : "audio\/x-wav",
".xhtml" : "application\/xhtml+xml",
".xml" : "application\/xml",
".zip" : "application\/zip"
};