1
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

node.jsでWebスクレイピングを行い、選手名をcsvに出力する

Last updated at Posted at 2019-04-24

初投稿ですm(_ _)m
読売ジャイアンツの支配下登録選手の一覧が必要になりました(私用で)。
そんなに数が多くないのでコピーして整形してペーストでもいいのですが、以前Webスクレイピングが思っていたよりも簡単にできる!という記事を見かけたのでやってみる事にしました。
初心者ですので内容はご容赦ください。

対象サイト

参考にさせて頂いた記事

https://qiita.com/tokutatsu/items/5c0d8e9217555a7ac724
https://qiita.com/ta1nakamura/items/105db4de2980ff224de8

スクレイピング

Node.jsのモジュール、cheerio-httpcliを使用しスクレイピングを行います。

静的ページであればHTMLをjQeryのように扱うことができるので、初心者の私でも操作しやすいと思いこちらを選択しました。

csvファイルに出力

csv-writerというモジュールを使用し、指定するcsvファイルにスクレイピングで取得した選手名を書き込みます。

やってみた

選手や監督名は.rosterRegisterクラスでまとめられているので、その中のテキストを取得し、csvに出力します。

const {createObjectCsvWriter} = require('csv-writer');
const client = require('cheerio-httpcli');

const csvFilePath = 'data.csv'
const csvWriter = createObjectCsvWriter({
    path: csvFilePath,
    header: [
        {id: 'name', title: 'NAME'}
    ],
    encoding:'utf8',
    append :false,
});

const players = [];

client.fetch('http://npb.jp/bis/teams/rst_g.html',)
    .then((result) => {
        // テキストを配列に格納
        result.$('.rosterRegister').each(function (idx) {
            const $player = result.$(this).text();
            players.push({name: $player});
        });
        // csvファイルに書き込み
        csvWriter.writeRecords(players)
            .then(() => {
                console.log('...書き込み完了');
            });

    })
    .catch((err) => {
        console.log(err);
    })
    .finally(() => {
        console.log('終了!');
    });

感想

本当に初心者の僕でも簡単にできた!
今回はやりたい事が単純で実装も楽々でしたが、もう少し拡張すれば選手のデータとかも取得し出力できそうだなと思いました。
色々動かしてみて遊んでみようかなと思います!

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?