Skip to content

WIN32OLE

基本

require 'win32ole'

ie = WIN32OLE.new("InternetExplorer.Application")
ie.visible = true
ie.navigate("http://google.co.jp")
while ie.busy == true; sleep 0.5; end

puts ie.document.title

AUTOIE

require './AUTOIE.rb'
include AUTOIE
AUTOIE.rb
# coding: utf-8
require 'win32ole'
require 'pp'
require 'win32ole_pp'

module AUTOIE

  def ie_wait()
    while @ie.busy == true; sleep 0.5; end
  end

  def self.find_ie_by_url(url)
    sleep 1
    shell = WIN32OLE.new("Shell.Application")
    windows = shell.Windows
    ie = nil
    windows.each do |w|
      if w.locationURL.include?(url)
        ie = w
        puts "------------------------------------------------------------"
        puts "  ole_type.name: #{ie.ole_type.name}"  #=> IWebBrowser2
        puts "   locationName: #{ie.locationName}"
        puts "    locationURL: #{ie.locationURL}"
        puts "------------------------------------------------------------"
        break
      end
    end
    if ie.nil?
      puts "---- No Window has detected. ----"
      ie = WIN32OLE.new("InternetExplorer.Application")
      ie.visible = true
    end
    @ie = ie
    ie
  end

end

TIPS

メソッド一覧

puts ie.document.body.methods
puts ie.document.body.ole_methods
require 'win32ole'
require 'pp'
require 'win32ole_pp'

hoge.ole_methods.map{|m|p m};0

window

window = ie.document.ParentWindow

frame

ie.document.frames.item(0).document.getElementsByName

子ウィンドウ

OS上のWIN32OLEウィンドウを対象に指定のウィンドウを探索し、変数ieに格納し直すことで操作対象とする。

require 'win32ole'

ie = WIN32OLE.new("InternetExplorer.Application")
ie.visible = true
ie.navigate("http://www.google.co.jp")
while ie.busy == true; sleep 0.5; end

ie = WIN32OLE.new("InternetExplorer.Application")
ie.visible = true
ie.navigate("http://www.yahoo.co.jp")
while ie.busy == true; sleep 0.5; end

shell = WIN32OLE.new("Shell.Application")
windows = shell.Windows
windows.each do |w|
  puts "ole_type.name: #{w.ole_type.name}"  #=> IWebBrowser2
  puts "  locationURL: #{w.locationURL}"
  ie = w if w.locationURL.include?("www.google.co.jp")
end
ie.document.parentwindow.alert("This is current 'ie' target.")

JavaScript の関数を呼び出す

  • rubyからJavaScriptの関数を起動する方法は?
    function sayHello(msg) {
      window.alert(msg);
    }
    function introduce(name, age) {
      window.alert("My name is " + name);
      window.alert("I am " + age + "years old");
    }
    
    ie.document.parentWindow.sayHello._invoke 0, ['Hello'], [WIN32OLE::VARIANT::VT_BSTR]
    ie.document.parentWindow.introduce._invoke 0, ['John', 20], [WIN32OLE::VARIANT::VT_BSTR, WIN32OLE::VARIANT::VT_INT]
    
    cf. module WIN32OLE::VARIANT

モーダルダイアログ(alert, confirm)のボタン対処

main.rb

Thread.start { `push-enter.cmd` }
sleep 1.5
ie.document.parentWindow.alert("Hi.")
push-enter.cmd
push-enter.vbs
push-enter.vbs
Set sh = WScript.CreateObject("WScript.Shell")
WScript.Sleep 1500
sh.AppActivate("The Window Title")
WScript.Sleep 1500
sh.SendKeys "{ENTER}"