Skip to content

Instantly share code, notes, and snippets.

@syon
Created May 1, 2017 03:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save syon/2d1c451790c32edc40e0f916d7c06de5 to your computer and use it in GitHub Desktop.
Save syon/2d1c451790c32edc40e0f916d7c06de5 to your computer and use it in GitHub Desktop.
OGP with cheerio on Node.js (Sample)
const fetch = require('node-fetch');
const cheerio = require('cheerio');
urls = []
urls.push('http://qiita.com/horike37/items/b295a91908fcfd4033a2')
urls.push('http://qiita.com/ryo0301/items/7f9fd8024987526cbc30')
urls.push('http://inokara.hateblo.jp/entry/2017/04/30/092304')
urls.push('https://togetter.com/li/1105672')
urls.push('https://allabout.co.jp/gm/gc/469010/')
urls.push('http://anond.hatelabo.jp/20170429110724')
urls.push('http://internet.watch.impress.co.jp/docs/news/1055983.html')
urls.push('http://qiita.com/chanibarin/items/48d5f5946b1e6c97e379')
urls.push('http://gigazine.net/news/20170410-pix-dt350n/')
urls.push('http://www.coconoodollblog.net/entry/2017/04/17/%E3%80%8C%E3%81%A7%E3%81%8D%E3%81%9F%EF%BC%81_%E3%83%AD%E3%83%95%E3%83%88%E3%82%92%E4%BD%9C%E3%82%8A%E3%81%BE%E3%81%97%E3%81%9F%E3%80%82%E2%91%A1%E3%80%8D%E6%97%A5%E6%9B%9C%E5%A4%A7%E5%B7%A5%E5%A5%B3')
urls.push('http://www.dtmstation.com/archives/51994323.html')
urls.push('http://www.itmedia.co.jp/news/articles/1704/07/news058.html')
urls.forEach((url) => {
const info = getPageInfo(url)
info.then(data => {
console.log('=============================')
console.log(data)
})
})
async function getPageInfo(url) {
const metaProps = await getMetaProps(url)
const site_name = resolveSiteName(metaProps)
const title = resolveTitle(metaProps)
const description = resolveDesc(metaProps)
const image = resolveImageUrl(metaProps)
return { site_name, title, description, image }
}
function resolveSiteName(metaProps) {
const ogSiteName = getMetaPropContent(metaProps, 'og:site_name')
if (ogSiteName) return ogSiteName
return '(No SiteName)'
}
function resolveTitle(metaProps) {
const ogTitle = getMetaPropContent(metaProps, 'og:title')
if (ogTitle) return ogTitle
return '(No Title)'
}
function resolveDesc(metaProps) {
const ogDesc = getMetaPropContent(metaProps, 'og:description')
if (ogDesc) return ogDesc
return ''
}
function resolveImageUrl(metaProps) {
const ogImage = getMetaPropContent(metaProps, 'og:image')
if (ogImage) return ogImage
return ''
}
function getMetaPropContent(metaProps, propKey) {
const mpObj = metaProps.find((d, i, arr) => {
return d[propKey]
})
if (mpObj) return mpObj[propKey]
return ''
}
async function getMetaProps(url) {
const result = await fetch(url).then(res => {
if (res.ok) { return res.text() }
}).then(html => {
const metaProps = extractMetaProps(html)
return metaProps
}).catch(e => {
throw e
})
return result
}
function extractMetaProps(html) {
const $ = cheerio.load(html)
let results = []
$('head meta').each((i, el) => {
const property = $(el).attr('property')
const content = $(el).attr('content')
if (property && content) {
results.push({ [property]: content })
}
})
results.sort((a,b) => {
if (Object.keys(a)[0] < Object.keys(b)[0]) return -1
if (Object.keys(a)[0] > Object.keys(b)[0]) return 1
return 0
})
return results
}
@syon
Copy link
Author

syon commented May 1, 2017

Result

=============================
{ site_name: 'INTERNET Watch',
  title: 'Microsoft、タスク管理アプリ「Microsoft To-Do」のプレビュー版をリリース、Wunderlistの機能を統合 ',
  description: ' 米Microsoftは19日、タスク管理アプリ「Microsoft To-Do」のプレビュー版を公開した。Windows版(Windows 10、Windows 10 Mobile)、iPhone版、Android版、ウェブ版をラインアップする。',
  image: 'http://internet.watch.impress.co.jp/img/iw/list/1055/983/01.jpg' }
=============================
{ site_name: 'ITmedia NEWS',
  title: 'Twitter、サードパーティー開発者の信頼回復目指しAPI統合とロードマップ公開',
  description: 'Twitterが、“複雑になっていた”開発者との関係の改善を目指し、「Twitter API Platform」の統合と開発ロードマップの公開を発表した。',
  image: 'http://image.itmedia.co.jp/news/articles/1704/07/l_yu_twitdev1.jpg' }
=============================
{ site_name: '藤本健の“DTMステーション”',
  title: 'iOSのDTM基幹ソフトがMIDIにも対応。Audiobus 3リリース : 藤本健の“DTMステーション”',
  description: 'iPhone、iPadのCPUが強化されてきたのに伴い、DAWやシンセサイザ、エフェクトなどもどんどん強力になってきているのと同時に、複数のアプリを同時に起動し、組み合わせて利用するのが当たり前になってきています。その組み合わせのための仕組みとして用意されているのがInter',
  image: 'https://farm3.staticflickr.com/2831/33129980033_35045d4a90_z.jpg' }
=============================
{ site_name: '[スマートフォン] All About',
  title: 'USB Type-Cについてあまり知られていない7つの事実',
  description: 'さまざまな機器に使用され、デファクト・スタンダードとなりつつあるUSB Type-C。しかし、同じType-Cと言っても実はさまざまな種類があり、性能も違っている。そこで、USB Type-Cにはどんな種類があり、どんな性能差があるのかを解説していく。',
  image: 'https://imgcp.aacdn.jp/img-a/1200/900/aa/gm/article/4/6/9/0/1/0/201704281349/topimg_original.jpg' }
=============================
{ site_name: 'Qiita',
  title: 'Firebaseを使うと簡単にユーザ属性毎のプッシュ通知が送れて既読管理やコンバージョンも簡単に把握することが出来るよ!しかも無料で!すごく魅力的だけどめっちゃハマった話  - Qiita',
  description: 'Firebaseを使うと簡単にユーザ属性毎のプッシュ通知が送れて便利機能も色々付いていてすごく魅力的なのですが、情報が少なくてハマった話です。\n※本稿ではiOSやAndroidへの実装方法には触れません\n# TL;DR\n- Fireb...',
  image: 'http://cdn.qiita.com/assets/qiita-fb-2887e7b4aad86fd8c25cea84846f2236.png' }
=============================
{ site_name: 'はてな匿名ダイアリー',
  title: '美大生との合コンがやばすぎた。',
  description: 'しがない大学生なんだけど最近免許の更新で二俣川の試験場にいったらエスペランサスポルディングみたいなアフロヘアの女にいきなり逆ナンされ…',
  image: 'http://anond.hatelabo.jp/images/og-image-1500.gif' }
=============================
{ site_name: 'Togetter',
  title: '星野源さん、テレビ番組で「人見知り」についての持論を述べる「すごく納得した」「耳が痛い」',
  description: 'まとめました。 更新日:4月30日10時41分',
  image: 'http://pimg.togetter.com/71305999faaf922e03162f8528ea7f9e04a00891/68747470733a2f2f7062732e7477696d672e636f6d2f6d656469612f432d6c6a69474955514145304551612e6a70673a6c61726765?w=1200&h=630&t=c' }
=============================
{ site_name: 'Qiita',
  title: 'S3に画像をアップロードしたらLambdaでサムネイルを生成する(node-imagemagick) - Qiita',
  description: '\n公式ドキュメントでは gm でサムネイルを作っているが node-imagemagick が入っているのでそのまま貼れば一応動く。\nnode-imagemagick はメンテされてないので gm を使ったほうがいいとは思う。\n\nht...',
  image: 'http://cdn.qiita.com/assets/qiita-fb-2887e7b4aad86fd8c25cea84846f2236.png' }
=============================
{ site_name: 'Qiita',
  title: 'Serverless Framework v1.0の使い方まとめ - Qiita',
  description: '# 概要\n<img width="1039" alt="スクリーンショット 2016-10-17 0.53.48.png" src="https://qiita-image-store.s3.amazonaws.com/0/65478...',
  image: 'http://cdn.qiita.com/assets/qiita-fb-2887e7b4aad86fd8c25cea84846f2236.png' }
=============================
{ site_name: 'GIGAZINE',
  title: 'iPhone・iPadで地デジ放送を高画質で視聴&録画できるフルセグチューナー「PIX-DT350N」レビュー',
  description: 'Android端末にはワンセグだけでなくフルセグチューナーを搭載して地デジ番組を高画質で視聴できるものもありますが、iPhoneやiPadにはチューナーが内蔵されていないのでこれは不可能です。しか',
  image: 'http://i.gzn.jp/img/2017/04/10/pix-dt350n/00_m.jpg' }
=============================
{ site_name: 'coconoo doll',
  title: '「できた! ロフトを作りました。②」日曜大工女子の活動。 - coconoo doll',
  description: '里山の人形師 coconooです。 こんにちは。 この土日はロフトを作っていました。 www.coconoodollblog.net 家の梁に「根太」を渡して、 その上に、サブロクの合板の板を貼ってゆき 出来上がり!!! 下から見ると、こんな感じ。 以前作った、台所上のロフトとつなげました。 「あ~~~板、重かった…。」 また、収納場所を増やしてしまいました…。(笑) 今日も、来てくださって、ありがとうございます。',
  image: 'https://cdn-ak.f.st-hatena.com/images/fotolife/c/coconoo/20170416/20170416184113.jpg' }
=============================
{ site_name: 'ようへいの日々精進XP',
  title: '俺は Linux コンテナについてなんにも解っていなかった 〜 haconiwa で学ぶ Linux コンテナ (1) 〜 - ようへいの日々精進XP',
  description: '直近の Docker 界隈について Linux コンテナ 参考 Linux コンテナとは Linux コンテナを構成する主な機能 OS リソース毎の Namespace cgroup サブシステム こんなにざっくりでは、Linux コンテナは語れないと思うけど haconiwa haconiwa とは haconiwa で何が出来ると? haconiwa 導入 はじめての haconiwa (1) はじめての haconiwa (2) 〜 コンテナ作成 〜 はじめての haconiwa (3) 〜 コンテナ起動 〜 haconiwa で学ぶ Linux コンテナ .haco ファイル再掲 na…',
  image: 'https://cdn.image.st-hatena.com/image/scale/f2a291bf5d0f33753db956b12610dd35ea57b388/backend=imager;enlarge=0;height=1000;version=1;width=1200/https%3A%2F%2Fcdn.mogile.archive.st-hatena.com%2Fv1%2Fimage%2Finokara%2F297795448778160892.gif' }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment