require "selenium-webdriver"
require "net/http"
require "uri"
require "fileutils"
require "securerandom"
def unzip(input)
basename = File.basename(input).sub(File.extname(input), "")
dirname = File.dirname(input)
output = nil
idx = 0
loop do
if idx == 0 then
output = dirname + "/" + basename
else
output = dirname + "/" + basename + "[" + idx.to_s + "]"
end
break unless File.exist?(output)
idx += 1
end
ret = `7z.exe x -y -r -p "#{input}" -o"#{output}"`
if ret.include?("Everything is Ok") then
FileUtils.rm_rf(input)
return true
else
FileUtils.rm_rf(output) if File.exist?(output)
return false
end
end
driver = nil
bin_dir = "C:/Ruby31-x64/bin/"
if File.exists?("#{bin_dir}/chromedriver_tmp.exe") then
FileUtils.rm_rf("#{bin_dir}/chromedriver.exe")
FileUtils.cp("#{bin_dir}/chromedriver_tmp.exe", "#{bin_dir}/chromedriver.exe")
FileUtils.rm_rf("#{bin_dir}/chromedriver_tmp.exe")
end
begin
options = Selenium::WebDriver::Options.chrome
options.page_load_strategy = :normal
driver = Selenium::WebDriver.for :chrome, options: options
driver.get("https://www.google.co.jp")
rescue => e
full_message = e.full_message
if (full_message =~ /This version of ChromeDriver only supports Chrome version ([0-9]+)/) then
_major_ver_name = full_message.scan(/Current browser version is ([0-9]+)/)
if (_major_ver_name.size > 0) then
major_ver_name = _major_ver_name[0][0]
response = Net::HTTP.get(URI.parse("https://chromedriver.chromium.org/downloads"))
if !response.scan(/href=\"https:\/\/chromedriver\.storage\.googleapis\.com\/index\.html\?path=(#{major_ver_name}\.[0-9\.]*)\//).empty? then
tmp_dir = "C:/Users/toshi/Desktop/tmp#{SecureRandom.alphanumeric}"
FileUtils.mkdir_p(tmp_dir)
full_ver_name = response.scan(/href=\"https:\/\/chromedriver\.storage\.googleapis\.com\/index\.html\?path=(#{major_ver_name}\.[0-9\.]*)\//)[0][0]
response2 = Net::HTTP.get(URI.parse("https://chromedriver.storage.googleapis.com/#{full_ver_name}/chromedriver_win32.zip"))
File.open("#{tmp_dir}/chromedriver_win32.zip", "wb") do |f|
f.write(response2)
end
unzip("#{tmp_dir}/chromedriver_win32.zip")
FileUtils.mv("#{tmp_dir}/chromedriver_win32/chromedriver.exe", "#{bin_dir}/chromedriver_tmp.exe")
FileUtils.rm_rf(tmp_dir)
end
end
end
end
driver.quit if (driver != nil)
