意外と情報がなく、意外とはまったため。
準備
-
公式がasync/awaitが多いので一応予習
-
それに伴いnode.jsは8系(LTS基準)
-
適当なディレクトリを作る
-
npm init -
npm i puppeteer -
エラーを吐くindex.htmlの作成
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>test page</title>
</head>
<body>
<img src="http://placeholder.via/50x50" alt="" />
<img src="hoge.png" alt="" />
<script>
console.log('hoge')
console.log(hoge)
</script>
</body>
</html>
- puppeteerのコード index.jsの作成
const puppeteer = require('puppeteer')
;(async () => {
const browser = await puppeteer.launch()
const page = await browser.newPage()
// consoleに出るエラーの検知
page.on('pageerror', (error) => {
console.log('consoleに出てるエラーだよ', error.message)
})
// 各リクエストのレスポンスを検知
page.on('response', (response) => {
console.log(response.status(), response.url()) // 全リクエストのステータスコードとURLをlog
if (300 > response.status() && 200 <= response.status()) return
console.warn('status error', response.status(), response.url()) // ステータスコード200番台以外をlog
})
await page.goto('http://localhost:3000/', { waitUntil: 'networkidle2' })
await browser.close()
})()
- package.jsonのscriptsの調整(やらなくても良い)
{
"scripts": {
"serve": "python -m SimpleHTTPServer 3000 index.html",
"test": "node index.js"
}
}
npm run serve- 別タブで
npm test
(こういう複数コマンドを適当に実行する方法が何かあった気がするものの忘れたのでわかる方いたらコメント頂けたらとてもとてもうれしいです。(serve->test))
結果
200 'http://localhost:3000/'
consoleに出てるエラーだよ ReferenceError: hoge is not defined
at http://localhost:3000/:13:15
404 'http://localhost:3000/hoge.png'
status error 404 http://localhost:3000/hoge.png
pageerrorやresponseが意外と見つからなかった。page.gotoの後に書いてあるコードもあったりしたものの当たり前な気もするもののpage.gotoの前に書かないといけなかった。