5

I'm opening a set of URLs with a WebDriver in ruby – kind of a slideshow with 3 seconds intervals between "slides" (pages). Person looking at that happening might click Space, and I need that page URL saved to another file. How could I handle those interruptions – catch the event of Space pressed?

require "watir-webdriver"

urls = [...list of URLs here...]
saved = []

b = Watir::Browser.new

urls.each do |url|
  b.goto url
  sleep(3)

  # ...what should I put here to handle Space pressed?

  if space_pressed
    saved << b.url
  end
end
earlyadopter
  • 1,537
  • 4
  • 16
  • 21
  • Where would you expect the space to be pressed? Do you mean in the browser or maybe the command prompt running the script? – Justin Ko Dec 02 '13 at 19:24
  • @justin-ko: either will work for me. I tried solution offered here http://stackoverflow.com/questions/946738/detect-key-press-non-blocking-w-o-getc-gets-in-ruby but wasn't able to catch any keys pressed in the browser (nothing happens) or command line (it displays pressed keys, but with no effect on the script running). – earlyadopter Dec 02 '13 at 23:08

1 Answers1

3

It looks like your problem might be solvable with STDIN.getch.

If you create a file with the following script and then run it in a command prompt (eg "ruby script.rb"), the script will:

  1. Navigate to the url.
  2. Ask if the url should be captured.
  3. If the user does not input anything in 10 seconds, it will proceed onto the next url. I changed it from 3 since it was too fast. You can change the time back to 3 seconds in the line Timeout::timeout(10).
  4. If the user did input something, it will save the url if the input was a space. Otherwise it will ignore it and move on.

Script:

require "watir-webdriver"
require 'io/console'
require 'timeout'

urls = ['www.google.ca', 'www.yahoo.ca', 'www.gmail.com']
saved = []

b = Watir::Browser.new

urls.each do |url|
  b.goto url

  # Give user 10 seconds to provide input
  puts "Capture url '#{url}'?"
  $stdout.flush
  input = Timeout::timeout(10) {
    input = STDIN.getch
  } rescue ''

  # If the user's input is a space, save the url
  if input == ' ' 
    saved << b.url
  end
end

p saved

A couple of notes:

  • Note that the inputs need to be to the command prompt rather than the browser.
  • If the user presses a key before the allotted timeout, the script will immediately proceed to the next url.
Justin Ko
  • 46,526
  • 5
  • 91
  • 101
  • Justin, could you think of any way to make it let's say down-arrow instead of Enter to go to the next URL? And - yes, some one key ("s" for example as a shortcut for "save") instead of s-Enter could have been so much nicer. I probably will need to find a way for $stdin to expect only one key, and not (some_entry)+Enter. – earlyadopter Dec 03 '13 at 00:18
  • Okay, after some more digging, I found some core libraries that can be combined to do what we need (ie no longer needs enter key). Try this updated answer. – Justin Ko Dec 03 '13 at 02:08