LoginSignup
4

More than 5 years have passed since last update.

cheerio-httpcli でログインした後にファイルをダウンロードする

Last updated at Posted at 2018-01-22

cheerio-httpcli でログインした後にファイルをダウンロードする

cheerio-httpcliというスクレイピングライブラリを使って、会員制のアップローダーにログインした後にファイルをダウンロードしたかったけど、ライブラリ自体にはダウンロード機能がなくて躓いたので、ここにメモを残しておきます。

ライブラリ自体の使い方の説明はしないので、大雑把に雰囲気をつかみたい人は、作者の紹介記事、詳しい使い方を知りたい人は、README.mdを読んで下さい

ログインする

const client = require('cheerio-httpcli')

client.fetch('http://example.com/login').then(result => {
  result.$('form[name=login]').submit({
    user: 'hoge',
    pass: 'fuga',
  }, (err, $, res, body) => {
    // フォーム送信後に移動したページ取得後の処理
  })
})

普通にログインするだけで、作者の紹介記事や、リポジトリにもサンプルがあるので説明は割愛。

ファイルをダウンロードする

前提としてログインしないと、ファイルがダウンロードできず、エラーページに飛ばされるのでCookieをセットする必要があるので、res.cookiesでCookieを取得して、リクエスト時にヘッダーにつける。

const fs = require('fs')
const request = require('request')
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // フォーム送信後に移動したページ取得後の処理(続き)
    const cookies = res.cookies
    request({
      url: 'http://example.com/example.zip',
      headers: {
        Cookie: Object.keys(cookies).map(e => e + '=' + cookies[e]).join('; '),
      },
      timeout: 60000,
      encoding: null,
    }).pipe(fs.createWriteStream('./example.zip'))

ポイントとしては

  • Cookieが変わっても動作するように直指定ではなく、全てのCookieをつなげている
  • バイナリデータを返すようにするためにencoding: nullを指定している

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
4