12
28

More than 5 years have passed since last update.

Pinterest APIで画像を取得する

Posted at

はじめに

Pinterestの特定のボードから画像をすべて取得したいなーと思ったときの自分用のメモ。
何度も実行するわけではなかったので、ブラウザで画像だけ一気に表示して保存してしまおうという魂胆。

ソースコード

早速ソースコードを晒しておく。

npm initしてpackage.jsonを作成し以下のような感じに。
これくらいならtypescriptなしで書けよという話かもしれませんが。。

package.json
{
  "name": "pinterest_dl",
  "version": "1.0.0",
  "description": "",
  "main": "index.html",
  "scripts": {
    "tsc": "tsc"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "jquery": "^3.1.1"
  },
  "devDependencies": {
    "@types/jquery": "^2.0.32",
    "typescript": "^2.0.3"
  }
}

次にHTML。

index.html
<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8" />
    <script src=".\node_modules\jquery\dist\jquery.min.js"></script>
    <script src=".\src\index.js"></script>
</head>

<body>
    <div id="images"></div>
</body>

</html>

最後はmainとなるTypeScript。
コードを保存したあと、npm run tsc initしてtsconfig.jsonを作る。
excludeにnode_modulesを追加する。

tsconfig.json
{
    "compilerOptions": {
        "module": "commonjs",
        "target": "es5",
        "noImplicitAny": false,
        "sourceMap": false
    },
    "exclude": [
        "node_modules"
    ]
}

以下のコードを作成したあと、npm run tscをルートフォルダで実行すればトランスパイルされる。

src/index.ts
function getImages(url: string): string[] {
    console.log(url);
    if (url !== undefined && url !== null && url !== "") {
        $.getJSON(url)
            .done(function (res) {
                console.log(res);
                res.data.forEach(element => {
                    $('#images').append('<img src="' + element.image.original.url + '">');
                });
                console.log(res.page.next);
                getImages(res.page.next);
            });
    } else {
        return [];
    }
}

var token: string = "<pinterest token>";
var userId: string = "<your userId>";
var boardName: string = "<your board name>";
var link: string = "https://api.pinterest.com/v1/boards/" + userId + "/" + boardName + "/pins/?access_token=" + token + "&fields=image";

getImages(link);

Pinterest APIのトークンなどは以下のサイトから取得しておくと便利。

注意点は、このAPIから返ってくるJSON文字列は25枚の画像しかない。
次の画像へのURLはpage.nextに入っているのでそこを参照していくと連続して取得できる。

おわりに

完成したらindex.htmlをブラウザで表示。たくさんの画像のみが表示された!
いろんなサービスがどんどんAPIを実装してくれているから非常に助かるなーと思う次第でした。

12
28
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
12
28