Quantcast
Channel: Node.jsタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 8704

Node.js でお手軽スクレイピング 2020 年夏(cheerio版) ポエム

$
0
0

まずは環境から。

$ node -v
v12.16.1

そしてプロジェクトの初期化を行って、2 つほどライブラリをインストールします。

$ npm init -y$ npm install node-fetch cheerio --save-dev

必要なライブラリが揃ったところで早速スクリプトを書いていきましょう。サンプルに気象庁の東京都の週間天気予報のページを選びました。

index.js
#!/usr/bin/env node
constfetch=require('node-fetch');constcheerio=require('cheerio');constmain=async()=>{constres=awaitfetch('https://www.jma.go.jp/jp/week/319.html');if(res.status!==200){console.log(`error status:${res.status}`);return;}// jqueryチックに使えるように変換const$=cheerio.load(awaitres.text());constnodes=$('#infotablefont tr:nth-child(4) td');nodes.map(function(i){console.log(nodes.eq(i).text().trim());});};main();

そのコードをスクリプトファイルに貼り付ければそれだけでもうスクレイピングの完成です。このスクリプトを実行すると以下のような結果が得られます。

$ ./index.js
曇時々雨
曇一時雨
曇
曇時々晴
曇時々晴
曇時々晴
曇時々晴

以上でスクリプトの解説は終わりです。

最後に、忘れてはならないのはスクレイピングは最終手段であるという事です。API が提供されているサービスであれば必ずそちらを使うべきですし、やむを得ずスクレイピングする際はサーバに過度な負荷を与えることの無いよう気をつけましょう。

参考記事

https://qiita.com/otchy/items/244c19c561ecb7211fa5


Viewing all articles
Browse latest Browse all 8704

Trending Articles