1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【LinkPreview API + Cheerio】Qiitaのサムネイルを取得する

Posted at

はじめに

QiitaAPIを使用して自分の記事一覧の取得を試みました。
その際に、サムネイル画像(OGP画像)を取得したいと考えましたが、方法がわからなかったため調べたことをまとめます。

問題

QiitaAPIから取得したURLを元にサムネイル画像を取得したい。

解決方法

LinkPreview APIを使用し、記事のHTMLを取得
Cheerioライブラリを使用し、og:imageプロパティのコンテンツを取得する

OGPは動的に生成されるため、HTMLページを直接解析して取得を試みました。

1.LinkPreview APIでAPIキーを発行する

Curlコマンドで実行すると、記事内容が取得できました。

curl "https://qiita.com/asa129/items/adc4a8e7782e89d4d524" -H "X-Linkpreview-Api-Key: 発行したAPIキー"

image.png

2.Cheerioライブラリを使用し、OGPを取得する

取得した内容の、下記タグcontent="URL"がサムネイル画像になります。
<meta property="og:image" content="https://qiita-user-contents.i~省略~23fded4">

cheerioを使用し、取得しました。

export const runtime = "nodejs";
import { load } from "cheerio";

export async function getOgpImage() {

    const url = "Qiita記事のURL";
    const res = await fetch(url, {
      headers: {
        "X-Linkpreview-Api-Key": "Linkpreviewで発行したAPIキー",
      },
    });
    const data = await res.text(); // html形式で取得
    const $ = load(data);
    const ogpImage = $("meta[property='og:image']").attr("content");

    console.log(ogpImage);
}

image.png

おわりに

サムネイルはOGP画像で作成されていることを知りました。
ひと手間必要なため、もう少し簡単に取得できるといいのになと思います。

参考

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?