Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby webdriver: how to catch key pressed while the script is running?

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
like image 348
earlyadopter Avatar asked Oct 21 '22 20:10

earlyadopter


1 Answers

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.
like image 126
Justin Ko Avatar answered Oct 24 '22 03:10

Justin Ko