簡単なpuppeteerの例



ツールと資料
  • QQ群-Javascriptプレミアム爬虫類(832946826)-作者自建群、ようこそ!
  • awesome-java-crawler-著者らが収集した爬虫類関連ツールと資料
  • 前言
    本シナリオの役割は、読書城の男性周波数と女性周波数の各分類の完結した書籍情報をつかみ、好評順に上位3ページだけをつかむことです.このページには逆行措置はなく、簡単な例として適しています.
    大まかな開発プロセス:
  • 手動分析ページ、解析URLとページング、分類などのキーパラメータ
  • 手動でページ内容を分析し、コンソール検証データ抽出方法
  • 符号化
  • コードの説明:
  • の前のpidsとcidsの2つの定数配列は、事前にページ上でハイパーリンク収集を表示しています.
  • データ抽出のためのfメソッドは、実際には文字列に変換するpageを通過する.evaluateはnode環境ではなくブラウザで実行されます.しかし、両側の言語が一致するため、nodeソースコードと直接書くことができ、IDEサポートを得ることができるが、他の言語ではjsコードは文字列形式で
  • しか存在しない.
  • puppeteerのpage.evaluateはブラウザ側スクリプトから返されたオブジェクトを直接node側に渡すことができ、非常に便利です.
    ソースコード
    const fs = require("fs")
    const puppeteer = require('puppeteer');
    
    const url = "http://www.ireader.com/index.php?ca=booksort.index&pca=booksort.index&pid=$pid&order=score&status=3&cid=$cid&page=$page"
    const pids = [10, 68]; //   ,  
    const cids = [[11, 27, 19, 22, 16, 39, 42, 50, 54, 57, 60], [69, 74, 82, 86, 89, 90, 91, 723]]; //       ID
    
    (async () => {
        const browser = await puppeteer.launch({ //   chrome   
            // headless: false, //       ,           ,               
            ignoreDefaultArgs: ["--enable-automation"], //   chrome      --enable-automation
        });
        const page = await browser.newPage();
        const f = () => {
            return Array.from($('.bookMation')).map(e => {
                const id = $('h3 a', e).attr('href').match(/bid=(\d+)/)[1] //          bid
                const title = $('h3 a', e).text()
                const author = $('p.tryread', e).text().replace('  ', '').trim()
                const desc = $('p.introduce', e).text()
                return {id, title, author, desc}
            })
        }
        let result = [];
        for (const i in pids) {
            const pid = pids[i]
            for (cid of cids[i]) {
                for (let pg = 1; pg < 4; pg++) { //      
                    const u = url.replace("$cid", cid).replace("$pid", pid).replace("$page", pg)
                    await page.goto(u);
                    const res = await page.evaluate(f)
                    res.forEach(e => { e.cid = cid; e.pid = pid })
                    result = result.concat(res)
                    console.log("page " + pg + " done")
                }
                console.log("cid " + cid + " done")
            }
            console.log("pid " + pid + " done")
        }
        fs.writeFileSync("d:/tmp/ireader_hot.json", JSON.stringify(result), {encoding: "utf-8"})
        console.log("all done")
          await browser.close(); //      
    })();