2020年8月30日日曜日

Note puppeteer Node.js

Node.js 12.18.3 puppeteer 5.2.1
pptr = require('./puppeteer_lib.js');
(async() => {
await pptr.BootBrowser();
await pptr.goto('http://wwwb.pikara.ne.jp/lllll/illl/form.htm');
await pptr.SetValueBySelector('#text1', 0, 'テキスト');
await pptr.SetValueBySelector('#password1', 0, '0123456');
await pptr.SetValueByXPath('//*[@id="textarea1"]',0,'テキストエリア');
await pptr.CheckeBySelector('input[name="radio1"]', ['test2']) ;
await pptr.CheckeBySelector('input[name="checkbox1"]', ['test1','test3']) ;
await pptr.SelectOptionsBySelector('select[name="select1"]',0, ['2']);
await pptr.SelectOptionsBySelector('select[name="select2"]',0, ['1','3']);
await pptr.SetUploadFileBySelector ('input[type="file"]', 0, 'C:/Users/PCUSER/Documents/index.php')
return 0;
})();
//'puppeteer_lib.js'

const puppeteer = require("puppeteer");
browser = null;
browserWSEndpoint = null;
TargetTab=null;


exports.BootBrowser=async () => {
    browser = await puppeteer.launch({
        headless: false /*ブラウザ表示:false*/
        , timeout: 30000
        , defaultViewport: null /*デフォルト800x600|効かない?*/
        , args: ['--start-maximized'  /*ウインドウ最大化*/, '--no-sandbox', '--disable-setuid-sandbox', '--disable-infobars']
        , executablePath: 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe'/*Chromium ではなく、Chromeを使用*/
        //,executablePath: 'C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe'/*Chromium ではなく、Edgeを使用*/
        //,executablePath: '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'/*Chromium ではなく、Chromeを使用*/
        //,userDataDir:'C:/Users/PCUSER/AppData/Local/Google/Chrome/User Data' //ユーザープロファイルを指定|要らない→/Default
    });
    browserWSEndpoint = await browser.wsEndpoint();
    TargetTab = (await browser.pages())[0];
    return browser.version();
}


exports.goto = async (url) => {
    await TargetTab._client.send('Emulation.clearDeviceMetricsOverride');
    await TargetTab.goto(url, { waitUntil: "networkidle2" });
    return 0;
}


exports.SetValueBySelectorX = async (selector, index, value) => {
    return await TargetTab.evaluate((data) => {
        return document.querySelectorAll(data.selector)[data.index].value = data.value;
    }, { selector, index, value });
}

//値を設定 セレクタで指定
exports.SetValueBySelector = async (selector, index, value) => {
    await TargetTab.waitForSelector(selector);
    const ElementHandle = await TargetTab.$$(selector);
    await ElementHandle[index].evaluate((el, value) => el.value = value, value);
    //await TargetTab.evaluate( (el,value) =>{ el.value = value}, JSHandle[index],value);
    const TextHandles = await ElementHandle[index].getProperty('value');
    const TextValue = await TextHandles.jsonValue();
    return TextValue;
}

//値を設定 XPathで指定
exports.SetValueByXPath = async function (XPath, index, value) {
    await TargetTab.waitForXPath(XPath);
    const ElementHandle = await TargetTab.$x(XPath);
    await ElementHandle[index].evaluate((el, value) => el.value = value, value);
    //await TargetTab.evaluate( (el,value) =>{ el.value = value}, ElementHandle[index],value);
    const TextHandles = await ElementHandle[index].getProperty('value');
    const TextValue = await TextHandles.jsonValue();
    console.log(TextHandles);
    return TextValue;
}

//SELECT オプションの値で選択 
exports.SelectOptionsBySelector = async (selector, index, OptionValueList) => {
    await TargetTab.waitForSelector(selector);
    const ElementHandle = await TargetTab.$$(selector);
    await ElementHandle[index].select();
    const result = await ElementHandle[index].evaluate((el, OptionValueList) => {
        const opt = el.options;
        const data = [];
        for (var i = 0; i < opt.length; i++) {
            if (OptionValueList.indexOf(opt[i].value) !== -1) {
                opt[i].selected = true;
                data.push(opt[i].value);
            }
        }
        return 0;
    }, OptionValueList);
    return JSON.stringify(result);
}

//ラジオボタン, チェックボックス を選択
//CheckeBySelector('input[name="radio1"]', ['test1','test2']) 
exports.CheckeBySelector = async (selector, ValueList) => {
    await TargetTab.waitForSelector(selector);
    const ElementHandle = await TargetTab.$$(selector);
    for (var i = 0; i < ElementHandle.length; i++) {
        const val = await ElementHandle[i].evaluate(el => el.value);
        if (ValueList.indexOf(val) !== -1) {
            await ElementHandle[i].evaluate(el => el.checked = true);
            console.log(val);
        } else {
            await ElementHandle[i].evaluate(el => el.checked = false);
        }
    }
    return 0;
}

//ファイルアップロード
//SetUploadFileBySelector ('input[type="file"]', 0, 'C:/Users/.../test.txt')
exports.SetUploadFileBySelector = async (selector, index, value) => {
    await TargetTab.waitForSelector(selector);
    const ElementHandle = await TargetTab.$$(selector);
    await ElementHandle[index].uploadFile(value);
    return 0;
}


exports.GetValueBySelector = async (selector, index) => {
    await TargetTab.waitForSelector(selector);
    const ElementHandle = await TargetTab.$$(selector);
    const TextHandles = await ElementHandle[index].getProperty('value');
    const TextValue = await TextHandles.jsonValue();
    return TextValue;
}

//GetPropertyBySelector ('html', 0 ,'outerHTML')
/*
href
textContent
value
innerText
outerText
innerHTML
outerHTML
etc.
*/
exports.GetPropertyBySelector = async (selector, index, propertyName) => {
    await TargetTab.waitForSelector(selector);
    const ElementHandle = await TargetTab.$$(selector);
    const TextHandles = await ElementHandle[index].getProperty(propertyName);
    const TextValue = await TextHandles.jsonValue();
    return TextValue;
};


0 件のコメント:

コメントを投稿