簡単なpuppeteerの例
2992 ワード
ツールと資料
本シナリオの役割は、読書城の男性周波数と女性周波数の各分類の完結した書籍情報をつかみ、好評順に上位3ページだけをつかむことです.このページには逆行措置はなく、簡単な例として適しています.
大まかな開発プロセス:
ソースコード
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(); //
})();