LoginSignup
4
4

More than 5 years have passed since last update.

【ruby】mechanizeで現在いるページのcookieとURLを取得

Last updated at Posted at 2017-03-21

mechanizeを使って、ログインした後のページでjsonファイルをスクレイピングしたいときに役立ったのでメモ:footprints:

jsonファイルを開く際にcookie情報を付与しよう

sq.rb
require 'mechanize'
require 'net/http'
require 'uri'
require 'open-uri'
require "json"


username = 'hoger'
password = 'hoge'

agent = Mechanize.new
page = agent.get('URL')

# login
login_form = page.forms[0]
  login_form.field_with(:name => 'identity').value = username
  login_form.field_with(:name => 'password').value = password
mypage = login_form.submit

# 現在いるページのURL
p mypage.uri.to_s

# cookie情報をゲット
cookie = agent.cookie_jar

# cookie情報を付与した状態でjsonファイルopen
# タイトル一覧をぶっこぬき

uri = URI.parse("jsonファイルpath")
request = Net::HTTP::Get.new(uri)
request["Cookie"] = cookie["hash"].to_s

req_options = {
  use_ssl: uri.scheme == "https",
}

response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
  http.request(request)
end
data = JSON.parse(response.body)

data.each { |e| p e["title"] }

cookieなどの情報を付与するときに便利

curl-to-rubyを使うと、JSONファイルを開く際に付与する必要な情報がすぐにわかるので、ソースコードを見比べてみてください!

参考

Mechanize::CookieJar

4
4
0

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
4