Login automation with website by Machanize with Ruby


Machanize library is used for automating integration with website.
If you are familiar with Ruby, this tool is pretty good for you.

By the way, this article describes a procedure to log in to a website.


🏀 Outline

  • Log in to a website by user name & password
  • Parse HTML which is showed after login by Nokogiri

🎂 Code

Add the following Gems to Gemfile and execute bundle install:

gem 'nokogiri'
gem 'mechanize'

Log in to the website and get parsed content from the HTML by Nokogiri:

require 'nokogiri'
require 'mechanize'

# Initialize & Configuration
agent = Mechanize.new
agent.user_agent_alias = 'Mac Safari 4'

agent.get('URL in login page') do |page|
# Login to a website
mypage = page.form_with(action: 'action tag') do |form|
form['user[name]'] = 'LOGIN USER NAME'
form['user[pwasswd]'] = 'LOGIN PASSWROD'
end.submit

# If you want to parse the result
doc = Nokogiri::HTML(mypage.content.toutf8)
h1_text = doc.css('h1').text
end

# If you want to get other page after logged in
other_page = agent.get('URL in some other page)
doc = Nokogiri::HTML(mypage.content.toutf8)
h1_text = doc.xpath('h1').text

🎉 Special Thanks

🖥 Recommended VPS Service

VULTR provides high performance cloud compute environment for you. Vultr has 15 data-centers strategically placed around the globe, you can use a VPS with 512 MB memory for just $ 2.5 / month ($ 0.004 / hour). In addition, Vultr is up to 4 times faster than the competition, so please check it => Check Benchmark Results!!