テトラポット技術ブログ「TetLab」

社会人3年目エンジニアのブログ。趣味での開発や仕事で得た知見などを書いて行こうと思います。

Node.jsとPythonでのスクレイピングメモ

バイト先でWebスクレイピングをする機会があったので、簡単ですがNode.jsとPythonでのWebスクレイピングをメモしておきます。

スクレイピングは、前回のブログ記事のタイトルを取得してみます。

環境

Node.jsの場合

モジュールは「cheerio-httpcli」を使用します。

モジュールのインストール

npm install cheerio-httpcli

コード

// モジュール読み込み
var client = require('cheerio-httpcli');

// URLを入力して、スクレイピング。
client.fetch('http://tetlab117.hatenablog.com/entry/2017/10/15/182158', {}, function (err, $, res) {

  // 記事のタイトルを取得
  $('title').each(function() {
    console.log($(this).text()); //タイトルを出力
  });

});

実行結果

f:id:tetrapod117:20171107152308p:plain

Pythonの場合

ライブラリは、requestsとBeautifulSoupを使用します。

ライブラリのインストール

pip install requests
pip install beautifulsoup4

コード

import requests
from bs4 import BeautifulSoup

target_url = 'http://tetlab117.hatenablog.com/entry/2017/10/15/182158' //URL
content = requests.get(target_url)         #requestsを使って情報を取得
soup = BeautifulSoup(content.text, 'lxml') #要素を抽出

print(soup.title.string)    //タイトルを出力

実行結果

f:id:tetrapod117:20171107152312p:plain

あとがき

タイトルを取得するくらいなら、NodeでもPythonのどちらでもかなり簡単にできますね。