管理系処理なら必須のログイン処理を作ってみました
2018/04/27の時点の最新のバージョン(V1.3)だと動かないので修正しました
設定ファイル
テスト用実行フォルダ/config.json
{ "SITE_ID": "masalib", "SITE_PW": "password" }
ログインするならこれは必要ですよね
git登録するならこの部分を除外設定かな
ログイン用のモジュール
//設定ファイルを読み込む const {SITE_ID, SITE_PW} = require('./config.json'); const cookies_path = './cookies_site.json'; /** * Cookieなしのログイン */ exports.loginproc = async function (page) { console.log(SITE_ID); console.log(SITE_PW); await page.goto('http://masalib.jp/admin/login.asp'); await page.screenshot({path: 'images/masalib_site_before_login.png'}); await page.focus('input[name=loginuser]'); await page.type('input[name=loginuser]',SITE_ID); await page.focus('input[name=passwd]'); await page.type('input[name=passwd]',SITE_PW); const inputElement = await page.$('input[type=submit]'); await inputElement.click(); await page.waitFor(2000); await page.screenshot({path: 'images/masalib_site_logined.png'}); }; /** * Cookieを利用してログイン */ exports.loginWithCookie = async function (page) { const cookies = JSON.parse(fs.readFileSync(cookies_path, 'utf-8')); for (let cookie of cookies) { await page.setCookie(cookie); } };
imagesのフォルダの存在チェックはしていません
本来はすべきかも
ログイン処理(main処理)
テスト用実行フォルダ/site_login.js
const puppeteer = require('puppeteer'); const fs = require('fs');//クッキー保存で使用 var loginmodule = require('./loginWithCookie.js');//ログイン用もモジュール (async () => { //headless: trueだと画面表示なしfalseなら画面あり const browser = await puppeteer.launch({ headless: true, }); const page = await browser.newPage(); await page.setViewport({width: 1280, height: 700}); await loginmodule.loginproc(page); const afterCookies = await page.cookies(); fs.writeFileSync('cookies_masalib_site.json', JSON.stringify(afterCookies)); browser.close(); })();
参考サイトと違う点
- テストサイトががクソ古くてclassもidも設定されていないのfocusの部分が違う
- サンプル側だとログインの入力時に
await page.waitFor(2000);
でまっているのですが待っていません
- 他の画面でも使いたかったのでログイン処理を別ファイルにした事です
Being Elmo: A Puppeteer's Journey
- 出版社/メーカー: Docuramafilms
- メディア: DVD
- この商品を含むブログを見る