30 Dec 2008, 4:03am
Work:
by Cliffano Subagio

1 comment
  • Image Saving In Watir

    So I got the chance to use Watir again on a short project at work. The last time I used it was about 1.5 years ago, and I was glad to find out that Watir is still a nice library to use. Watir simply works without much hassle.

    The only issue I had was with image saving. From Image class documentation (Watir 1.6), it wasn’t obvious that save can only be called when image element is directly contained within a browser element.

    I was trying to save the first image within a div,

    $browser.div(:id, 'foobar').images[1].save('d:\\temp')
    

    which resulted in this error

    NoMethodError: undefined method `goto' for #<Watir::Div:0x3fa5d7c>
    d:/dev/ruby/lib/ruby/gems/1.8/gems/watir-1.6.2/lib/watir/image.rb:113:in `save'
    

    Looking at the implementation of save in image.rb,

    def save(path)
      require 'watir/windowhelper'
      WindowHelper.check_autoit_installed
      @container.goto(src)
      begin
        thrd = fill_save_image_dialog(path)
        @container.document.execCommand("SaveAs")
        thrd.join(5)
      ensure
        @container.back
       end
    end
    

    it shows that save relies on the existence of goto and back methods within the container of the element, meaning that calling save method will tell the browser to go to the image src value, save it, and then click the back button. Hence image must be contained directly within a browser element.

    I ended up having to use XPath because the image element doesn’t have any id or class that allows me to directly reference it from a browser element.

    $browser.image(:xpath, "//div[@id='foobar']/img").save("d:\\temp")
    

    It would be nicer if @container can be replaced by something like find_root_container or something that traverses the ancestor container elements and eventually finds a browser element.

    Another nice improvement to the save method implementation would be instead of going to the image src and then clicking back, which could potentially lose the state of a page, it would be nicer to open a new window and close it afterward.

     

    Recent Posts

    Recent Comments

    • Neeraj Jaiswal: Maven is something which is a tool difficult to understand, but once you understand it becomes the...
    • Ronald Widha: bahhaaha…love the monitor shot!
    • Chess Strategizer: This just got bookmarked! “That’s why I always think of Simon Bolivar and remember that...
    • David: Thank you very much for sharing your wonderful tips! That would definitely be a great start for anyone who are...
    • Natasha: The quote “Find the best in everybody. Just keep waiting no matter how long it takes. No one is all...

    Most Commented Posts

    Linkroll