LoginSignup
16
18

More than 5 years have passed since last update.

puppeteerを使ってツイートを切り取って返すAPI

Last updated at Posted at 2017-09-04

puppeteerはHeadless Chromeであり、GoogleChrome公式が出しているだけあり安心感があり活用シーンが増えていくと思います。

GoogleChrome/puppeteer: Headless Chrome Node API

今回は、ツイートのurlをクエリとして与えると、そのツイートを切り取って返すAPIを書きました。

akameco/capture-tweet-api

cloneしてnpm startすればport 3000で動きます。
localhost:3000?url=ツイートのurlにアクセスすると、そのツイートのキャプチャが返ります。時間はかかりますが。

cap.png (812×690)

しかし、デモ画像の内容を見ればわかるとおり、aws lambdaにデプロイしようとしましたが以下の理由で失敗しました。
puppeteerはnode v7以上が要求されますが、aws lambdaのnodeのバージョンは6のためです。

Deploying on AWS Lambda · Issue #323 · GoogleChrome/puppeteer

また、デプロイサイズ的にもちょっと問題があります。
上記のイシューにもあるように、AWS lambdaの今後に期待といったところです。


また、要素を切り取ってキャプチャする処理はライブラリにしました。

akameco/capture-element

こんな感じで、urlと切り取りたい要素を指定すればキャプチャが取得できます。

const fs = require('fs');
const captureElement = require('capture-element')

captureElement(
  'https://github.com/akameco',
  '.js-calendar-graph'
).then(buffer => {
  fs.writeFileSync(buffer, 'github.png')
})

これを使ってGitHubの草状況を切り取るライブラリや、モバイル版のツイートを切り取るライブラリもちょっと作ってみました。

akameco/capture-github-kusa

const fs = require('fs');
const captureGithubKusa = require('capture-github-kusa');

captureGithubKusa('akameco').then(img => {
  fs.writeFileSync('github.png', img)
})

image.png


akameco/capture-mobile-tweet

const fs = require('fs');
const cap = require('capture-mobile-tweet');

const tweet = 'https://mobile.twitter.com/akameco/status/904080083802923008'

cap(tweet).then(img => {
  fs.writeFileSync('mobile-tweet.png', img)
})

ちょっとしたスライドにツイートやGitHubの草を貼り付ける際に便利かもしれません。

何かあれば、コメントやTwitterで議論しましょう。

参考

Puppeteerを使って指定したDOMのみのスクリーンショットを取得する
http://qiita.com/tamanugi/items/8cc1266265457f13b9ea

16
18
0

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
16
18