mechanize, nokogiriをgemからインストール
gem install mechanize gem install nokogiri
スクリプトは以下のような形
#!/root/.rbenv/shims/ruby
require 'nokogiri'
require 'mechanize'
USER_NAME = "hoge"
PASSWORD = "hogehoge"
LOGIN_URL = "https://example.com/login"
TARGET_URL = "https://example.com/my-page"
agent = Mechanize.new
agent.user_agent_alias = "Mac Safari 4" // HTTPリクエストのユーザエージェントの項目
#######
# Login
#######
agent.get(login_url) do |page|
login_result = page.form_with(name: 'loginform') do |form|
form.log = user_name
form.pwd = password
end.submit
end
############################
# Get Any Info from Web Page
############################
agent.get(target_url) do |page|
html = Nokogiri::HTML(page.body)
html.css('.hoge-class').each do |title|
puts title.text.to_s
end
end
参考
1時間の作業を自動化して1分でやろう! MechanizeとNokogiriで。
Mechanizeでログインしてスクレイピングする


