Pixivの認証が必要なところの物を取るスクリプト

プログラミング勉強中です。拙いですが公開。

  • 構成物
    • pixiv.rb
    • config.yaml

pixiv.rb

#! ruby
require 'net/http'
require 'uri'
require 'yaml'
# 設定ファイル
CONFIG_FILE = 'config.yaml'

class AccessPixiv
  # InitializeでCookieを取得しHeaderも構築する
  # 成功:Trueを返す
  # 失敗:Falseを返す
  def initialize
    config = YAML.load_file(CONFIG_FILE)

    Net::HTTP.start('www.pixiv.net', 80) do |http|
      response = http.post('/index.php',
                           'mode=login&pixiv_id=' + config['pixiv_id'] + '&pass=' + config['pixiv_pass'],
                           'User-Agent' => config['user_agent']
                          )
      if disp_error(response) == true
        cookie = response['Set-Cookie'].split(',')
        @header = {
          'User-Agent' => config['user_agent'],
          'Cookie' => cookie[1]
        }
        return true
      else
        return false
      end
    end
  end

  # uriで指定されたページ内容を取得する
  # 成功:対象URIの内容を返す
  # 失敗:Falseを返す
  def get(uri)
    site = URI.parse(uri)
    Net::HTTP.start(site.host, 80) do |http|
      response = http.get(site.request_uri, @header)
      if disp_error(response) == true
        return response.body
      else
        return false
      end
    end
  end

  private
  # エラー表示用
  def disp_error(response)
    case response
    when Net::HTTPBadRequest
      puts 'Error 400'
    when Net::HTTPUnauthorized
      puts 'Error 401'
    when Net::HTTPForbidden
      puts 'Error 403'
    when Net::HTTPNotFound
      puts 'Error 404'
    when Net::HTTPInternalServerError
      puts 'Error 500'
    when Net::HTTPServiceUnavailable
      puts 'Error 503'
    else
      return true
    end
    return false
  end
end

config.yaml

pixiv_id  : 'ゆーざあいでぃ'
pixiv_pass: 'ぱすわーど'
user_agent: 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)'

使い方

pixiv = AccessPixiv.new
puts pixiv.get('http://www.pixiv.net/mypage.php')

これで認証がされた状態のmypage.phpの内容が表示されます。

pixiv = AccessPixiv.new
f = open('pixiv.jpg', 'wb')
f.puts pixiv.get('がぞうのあどれす')
f.close

とかやると認証しないと取れないでかい画像も取得して保存できます。


これを基礎にしていろいろ作ります。おわり。