Last active
April 3, 2022 08:38
-
-
Save ynakajima/d32e4ba08a5f47e0d4ad to your computer and use it in GitHub Desktop.
Nodejs の Requestモジュールでログインが必要なページをスクレイピングする方法
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* request モジュールの jar を利用してログインが必要なページを取得する | |
*/ | |
var request = require('request'); | |
// cookie jar をデフォルトで利用するように設定 | |
request = request.defaults({jar: true}); | |
// リクエスト処理 | |
request('ログインフォームのURL', { | |
form: {id: 'ID', password: 'PASSWORD'} // ログイン情報を送信 | |
}, function() { | |
request('会員専用ページのURL', function(err, res, body) { | |
// スクレイピングの処理等をする | |
}); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* cookie jar を使いまわすことも可能 | |
*/ | |
var request = require('request'); | |
/** | |
* ログインしてcookie jarを返す | |
* @param {function} callback function(err, jar) | |
*/ | |
function login(callback) { | |
// cookie jar オブジェクトを作成 | |
var jar = request.jar(); | |
// リクエスト処理 | |
request('ログインフォームのURL', { | |
jar: jar, // cookie jarオブジェクトを指定 | |
form: {id: 'ID', password: 'PASSWORD'} | |
}, function(err, res, body) { | |
// cookie jarオブジェクトをcallback | |
callback(err, jar); | |
}); | |
} | |
// ログイン時の cookie jarオブジェクトを使いまわす | |
login(function(err, jar) { | |
request('会員専用ページのURL', { | |
jar: jar // ログイン時に取得したcookie-jarを指定 | |
}, function(err, res, body) { | |
// スクレイピング処理等をする | |
} | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment