dayjournal memo

Total 975 articles!!

Node.js #012 – YouTube APIで検索結果を取得

Yasunori Kirimoto's avatar

Node.jsでYouTube APIで検索結果を取得したい場合は下記のように記述します。


まず、YouTube APIを利用するにはアカウント登録が必要になります。

Google Developers Console

node.js_012_01


下記サイトにAPIキーの取得方法が詳しく記載してあるので参考になります。 YouTube Data API


APIキーを取得できたら次に、npmでyoutube-nodeをインストールする必要があります。



npm install youtube-node

script.js


var Youtube = require('youtube-node');
var youtube = new Youtube();

var keyword = 'FOSS4G';
var limit = 10;

var items;
var item;
var title;
var id;
var URL;

    youtube.setKey('ここに入力');

    youtube.addParam('order', 'viewCount');
    youtube.addParam('type', 'video');
    youtube.addParam('regionCode', 'JP');

    youtube.search(keyword, limit, function(err, result) {
        if (err) { console.log(err); return; }
            items = result["items"];
            for (var i in items) {
                item = items[i];
                title = item["snippet"]["title"];
                id = item["id"]["videoId"];
                URL = "https://www.youtube.com/watch?v=" + id;

                console.log("title : " + title);
                console.log("URL : " + URL);
                console.log("-------------------------------");
            }
    })

script.jsを実行すると下記のように取得したAPIがコマンドプロンプトに表示されます。

node.js_012_02


APIキーの設定 :


youtube.setKey('ここに入力')

検索条件の設定 : keyword: 検索文字 , limit: 表示数 order: 並び順 , type: 検索対象 , regionCode: 国コード


var keyword = 'FOSS4G';
var limit = 10;

youtube.addParam('order', 'viewCount');
youtube.addParam('type', 'video');
youtube.addParam('regionCode', 'JP')

指定情報を抽出 :


youtube.search(keyword, limit, function(err, result) {
    if (err) { console.log(err); return; }
        items = result["items"];
        for (var i in items) {
            item = items[i];
            title = item["snippet"]["title"];
            id = item["id"]["videoId"];
            URL = "https://www.youtube.com/watch?v=" + id;

            console.log("title : " + title);
            console.log("URL : " + URL);
            console.log("-------------------------------");
        }
})


book

Q&A


  • 参考文献
[![JS+Node.jsによるWebクローラー/ネットエージェント開発テクニック](http://ecx.images-amazon.com/images/I/61DHJGf1uSL._SL160_.jpg)](http://www.amazon.co.jp/exec/obidos/ASIN/4883379930/dayjournal-22/ref=nosim/)
[JS+Node.jsによるWebクローラー/ネットエージェント開発テクニック](http://www.amazon.co.jp/exec/obidos/ASIN/4883379930/dayjournal-22/ref=nosim/)