Last active
November 16, 2018 02:45
-
-
Save paul-yamamoto/d44aa1ec82e9f940af91d86afe82ebd5 to your computer and use it in GitHub Desktop.
Pupeteerを使うときは try~finallyでbrowserをcloseする。 ref: https://qiita.com/tpyamamoto/items/35a8dc4e0ffc310cd65d
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//ページ内のatagのhrefを全部取得 | |
async function getAtagHref(url) { | |
let outputs = []; | |
const puppeteer = require('puppeteer'); | |
const browser = await puppeteer.launch(); | |
const page = await browser.newPage(); | |
await page.goto(url, {waitUntil: "domcontentloaded"}); | |
//ここでエラーが発生して終了 | |
throw new Error('無理やりエラー!'); | |
outputs = await page.$$eval('a', anchors => anchors.map(anchor => anchor.href)); | |
await browser.close(); | |
return outputs; | |
} | |
function main() { | |
try { | |
return getAtagHref('https://qiita.com/'); | |
} catch (e) { | |
console.log(e); | |
//なんかクローリングがうまく行かなかったらから配列を返して終了してほしい | |
return []; | |
} | |
} | |
main() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
await page.goto(url, {waitUntil: "domcontentloaded"}) | |
.catch(async()=>await browser.close()); | |
outputs = await page.$$eval('a', anchors => anchors.map(anchor => anchor.href)) | |
.catch(async()=>await browser.close()); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//ページ内のatagのhrefを全部取得 | |
async function getAtagHref(url) { | |
const puppeteer = require('puppeteer'); | |
const browser = await puppeteer.launch(); | |
try { | |
const page = await browser.newPage(); | |
await page.goto(url, {waitUntil: "domcontentloaded"}); | |
return await page.$$eval('a', anchors => anchors.map(anchor => anchor.href)); | |
} catch(e) { | |
// 何かしらエラー処理 | |
// 呼び出し元でcatchするのであればここのcatchは不要 | |
throw e; | |
} finally { | |
//例外が発生しても発生しなくてもここは必ず通る | |
await browser.close(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment