Nightmareでブラウザでの操作を自動化する
node.js最近、POSTWASHという洗濯代行サービスを使っている。 専用のカバンに詰めて集荷にきた人に渡すと、きれいに畳まれた洗濯ものが届く便利なサービスだ。 注文時にはWebのフォームから集荷、配達時間や支払い方法などを選ぶ必要があるんだが、毎週のことなのでこれを自動化してみる。
ブラウザの操作を自動化するのにNightmareを使う。 Electronを使っていて、PahntomJSより2倍くらい速く、簡潔に書ける。
$ npm install nightmare
Nightmare()
の引数にshow: true
を渡すとウィンドウが開いて実行し始める。
これで確認画面までいくのであとは注文ボタンを押すだけ。
ウィンドウが閉じないように最後にnightmare.end()
を呼んでいない。
const co = require('co');
const moment = require('moment')
const jst = +9
const Nightmare = require('nightmare');
const nightmare = Nightmare({
show: true,
waitTimeout: 3000,
gotoTimeout: 3000
});
const loginID = process.env.LOGIN_ID;
const loginPassword = process.env.LOGIN_PASSWORD;
moment.locale('ja');
const now = moment().utcOffset(jst)
const dayAfterTomorrow = now.add(2, 'days').format("YYYY年M月D日(ddd)");
const nextWeek = now.add(7, 'days').format("YYYY年M月D日(ddd)")
console.log(`${dayAfterTomorrow}~${nextWeek}`);
// IDとパスワードを入れてログイン
const login = () => nightmare
.goto('https://sv359.xserver.jp/~postwash/postwash.net/accounts/')
.type('#loginid', loginID)
.insert('#loginpw', loginPassword) // .insert() is faster than .type() but does not trigger the keyboard events.
.click('#submit')
.wait('#yokoso')
.evaluate(() => document.querySelector('#yokoso h5').textContent);
// 注文フォームを埋めていく
const order = () => nightmare
.goto('https://sv359.xserver.jp/~postwash/postwash.net/mypage/order.html')
.wait('#item\\[4\\]')
.check('#item\\[4\\]')
.insert('#itemnum\\[4\\]', '1')
.select('#pickup_date_request', dayAfterTomorrow)
.select('#pickup_time_request', '午前中(8時~12時)')
.wait(500) // #delivery_date_request が切り替わってしまうので少し待つ
.select('#delivery_date_request', nextWeek)
.select('#delivery_time_request', '午前中(8時~12時)')
.select('#payment', '代金引換')
.check('#agreement')
.click('#submit')
co(function *(){
yield login().then(
(result) => console.log(result), // ようこそ
(err) => console.log(err)
);
yield order();
// yield nightmare.end();
});