6
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

nodejsでスクレイピングするため cheerio-httpcli を使ってたが、弾かれるサイトが出てきたので、
Headless Chromeでスクレイピングできる Puppeteer に乗り換えた。

先に感想を書くと、完璧にスクレイピングできた。
PWAページでも描画されるまで待ってくれるし、取れない値はなさそう。
今後はこのPuppeteerをメインにスクレイピングするので、テンプレとしてコードを残す。

テンプレコード

qiitaのOrganization一覧から自社である「株式会社ゆめみ」の投稿数/いいね数を取得してみる。

ついでにコードでスクショも取ってみる。

const puppeteer = require('puppeteer')

try {
  (async () => {
    const browser = await puppeteer.launch()
    const page = await browser.newPage()
    await page.goto("https://qiita.com/organizations/yumemi", { waitUntil: 'networkidle2' })  //表示されるまで待つ
    await page.screenshot({path: 'qiita_screenshot.png'}) //スクリーンショット撮影

    //投稿数
    const itemSelector1 = "body > div:nth-child(4) > div.organizationHeader > div > div > div > div.col-sm-3 > div > div:nth-child(1) > div.organizationHeader_stats_value"
    var postsCount = await page.$eval(itemSelector1, item => item.textContent) //取得
    console.log(`投稿数:${postsCount}`)

    //いいね数
    const itemSelector2 = "body > div:nth-child(4) > div.organizationHeader > div > div > div > div.col-sm-3 > div > div:nth-child(2) > div.organizationHeader_stats_value"
    var thunbsUpCount = await page.$eval(itemSelector2, item => item.textContent) //取得
    console.log(`いいね:${thunbsUpCount}`)

    await browser.close() //後片付け
  })()
} catch (error) {
  console.error(error)
}

撮影したスクショ

await page.screenshot({path: 'qiita_screenshot.png'})で撮影した画像

qiita_screenshot.png

ちゃんと撮れてる!

結果

投稿数: 1166
いいね: 31231

バッチリ取得できた!

資料リンク

6
5
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?