2
2

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.

CheerioライブラリとNodejsでデータクロール

Last updated at Posted at 2019-03-10

チェリオとは何ですか?###

これはデータクロール用の非常に強力なJavaScriptライブラリです。このライブラリはjQuery Selector とよく似たCheerio Selectorを提供するため、関数の使用はjQuery Selectorの使用と似ています。簡単に言うと、jQueryを使用するときは、htmlコードを取得するためhtml()の関数を使って、要素プロパティを取得するためattr(name、value)を使うことなどで、jqueryライブラリとおなじみの関数を使用します。このライブラリのしくみについて詳しくは、こちらを参照してください。

新しいストーリーの章があるときに自動的に通知するデモアプリケーションを書く###

私たちのステップは次のよう:

  • ステップ1:物語の最新章のリストを取得する。
  • ステップ2:新たな章があるかどうかを知るために、JSONのファイルに格納されている章とこの章を比較して新たな章があるかどうかを知る。そのJSONのファイルがない場合は、作成する。
  • ステップ3:新しい章がある場合はストーリーを取得して、メールで通知を送る。

じゃ、始めましょう。
cheerioとrequestというライブラリのインストールする。(クロールしたいデータがあるウエブサイトをコールする)

npm install request --save
npm install nodemailer --save```

必要なライブラリの宣言をする

```const cheerio = require('cheerio');
const request = require('request');
const fs = require('fs');
const nodemailer =  require('nodemailer');```

次に、ストーリーページから最新の章を取得するためのクローラ関数を作成して、jsonファイルと比較する。

// ウエブサイトからデータを取得する関数
function Crawler()
{
// ウエブサイトへリクエストを送る
request('http://truyencv.com/pham-nhan-tu-tien-chi-tien-gioi-thien/', function (err, res, body)
{
// cheerio.load関数でデータを取得する
var $ = cheerio.load(body);
// 最新のストーリーの章を取得する
var newestChap = $('.list-overview .item .item-value a').text();
var obj = {
'newestChap' : newestChap
}
var json = JSON.stringify(obj);
// newchap.jsonファイルをあるかどうかチェクする
if (!fs.existsSync('newchap.json')) {
// ない場合は作成する
fs.writeFile('newchap.json', json, '', (err)=>{
if (err) throw err;
console.log('newchap.jsonを作成することができました!');
});
return;
}
// プロジェクトの中にnewchap.jsonファイルの内容を読む
fs.readFile('newchap.json', function readFileCallback(err, data)
{
if (err)
{
console.log('newchap.jsonファイルを読むことができません!');
return;
}
else
{
// JSONファイルから最新の章を取得する
obj = JSON.parse(data);
var dbChap = obj.newestChap;
// 2つの章を比較して違うばあい新章がある
if(newestChap !== dbChap)
{
// newchap.jsonファイルに新章を保存する
fs.writeFile('newchap.json', json, '', (err)=>{
if (err) throw err;
console.log('新章がある!');
console.log('newchap.jsonファイルを編集しました!');
});
// 新章のリンクを取得する
var detailUrl = $('.list-overview .item .item-value a').attr('href');
// 新章の情報を取得するためリクエストを作成する
request(detailUrl, (err, res, body)=>{
let cheerioDetail = cheerio.load(body);
let contentDetail = cheerioDetail('.truyencv-read-content .content').text();
// メールで通信する
sendEmail(newestChap,contentDetail);

                });
            }
            else{
                console.log('新章がありません!');
            }
        }
    });
})

}


次のように送信するためにnodemailerライブラリを使用してsendEmail関数を追加します。

function sendEmail(subject, content)
{
var transporter = nodemailer.createTransport({
service : 'gmail',
auth: {
user : 'yourmail@gmail.com',
pass : 'yourpassword'
}
});
var mailOptions= {
from : 'yourmail@gmail.com',
to: 'yourmail@gmail.com',
subject : 'ストーリーの名前は新章が創刊する' + subject,
text : content
}
transporter.sendMail(mailOptions, function(err, info){
if(err)
{
console.log('メールでエーラが発生しました: ', err);
}
else
{
console.log('メールを送りました:', info.response);
}
});
}


最後に、このCrawler操作を3秒ごとに繰り返すための関数をもう1つ書く。

var timer = setInterval(function() {
return Crawler();
}, 5000);


次に、コマンドウィンドウでserver.jsを実行し、メールが送信されるのを待ちます。
そこで、cheerioとnodejsを使ってクロールデモの簡単なデモを行う方法を説明しました。
読んでくれてありがとうございました。
2
2
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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?