セレニウムでクロームドライバのバージョンミスマッチがいちいちうざいので、自動適用するプログラム書いてみた。
require "selenium-webdriver"
require "mechanize"
require "open-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]
Mechanize.new.get("https://chromedriver.chromium.org/downloads").search('li a').each do |link_elem|
if (link_elem.inner_text =~ /ChromeDriver #{major_ver_name}/) then
tmp_dir = "C:/Users/toshi/Desktop/tmp#{SecureRandom.alphanumeric}"
FileUtils.mkdir_p(tmp_dir)
full_ver_name = link_elem.attributes["href"].value.scan(/path=([0-9\.]+)\//)[0][0]
uri_str = "https://chromedriver.storage.googleapis.com/#{full_ver_name}/chromedriver_win32.zip"
URI.open(uri_str) do |res|
IO.copy_stream(res, "#{tmp_dir}/chromedriver_win32.zip")
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
end
driver.quit if (driver != nil)