Skip to content

Instantly share code, notes, and snippets.

@akiyoshi83
Created December 30, 2017 13:57
Show Gist options
  • Save akiyoshi83/cb0b5cbb0a2a66b5851fc14df23aab2e to your computer and use it in GitHub Desktop.
Save akiyoshi83/cb0b5cbb0a2a66b5851fc14df23aab2e to your computer and use it in GitHub Desktop.
Selenium by ruby
require 'bundler/setup'
require 'io/console'
require 'utils'
DRIVER_PATH = File.absolute_path case Utils::os
when :osx
'./driver/chromedriver_mac64'
when :windows
'./driver/chromedriver_win64.exe'
when :linux
'./driver/chromedriver_linux64'
end
class MyBrowser
def initialize(debug: false)
@username = ''
@password = ''
@debug = debug
@driver = nil
self.create_browser
end
def create_browser()
options = Selenium::WebDriver::Chrome::Options.new()
options.add_argument('--headless') unless @debug
@driver = Selenium::WebDriver.for :chrome, driver_path: DRIVER_PATH, options: options
end
def goto(url)
@driver.navigate.to(url)
if @driver.find_element(id: 'login_form')
self.login()
end
end
def login()
ask_username_password
@driver.find_element(name: "username").send_keys(@username)
@driver.find_element(name: "password").send_keys(@password)
@driver.find_element(id: "login").click()
end
def ask_username_password
if @debug
@username = ENV['username'] if ENV['username']
@password = ENV['password'] if ENV['password']
end
if @username.empty?
print "USERNAME: "
@username = gets.chomp!
end
if @password.empty?
print "PASSWORD: "
@password = STDIN.noecho(&:gets)
end
end
end
#! /usr/bin/env ruby
$LOAD_PATH.unshift(File.expand_path('../lib', File.dirname(__FILE__)))
require 'bundler/setup'
require 'optparse'
require 'chrome_example.rb'
require 'selenium-webdriver'
args = {}
OptionParser.new do |parser|
parser.on('-d', '--debug') {|v| args[:debug] = v}
parser.on('-u', '--url URL') {|v| args[:url] = v}
parser.parse!(ARGV)
end
mb = MyBrowser.new(debug: args[:debug])
mb.goto(args[:url])
require 'rbconfig'
module Utils
def self.os
@os ||= (
host_os = RbConfig::CONFIG['host_os']
case host_os
when /mswin|msys|mingw|cygwin|bccwin|wince|emc/
:windows
when /darwin|mac os/
:osx
when /linux/
:linux
when /solaris|bsd/
:unix
else
:unknown
end
)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment