This guide will show you how to get started with Watir’s webdriver Ruby library.
Things you will need:
- Gem(Tool used to install Ruby packages)
- Webdriver for Firefox(Download)
I’m writing this script from a Windows Machine(yes, I know, Windows blows) but this will work on any OS.
First things first, we need to get your environment setup to run your scripts.
How to install all the drivers:
- Move the Firefox webdriver to your Ruby path.
On Windows this is on yourlocaldisk/Rubyxxxx/bin/
On Linux and MacOS, this is on whatever your install path for Ruby was/bin.
- Go to your command prompt or terminal and type:
gem install watir
Congrats! Your enviroment is all setup. Let’s get scripting
- Open up a new file and call it
- Start your file with a simple import statement:
- Initialize your browser instance in Watir with:
browser = Watir::Browser.new :firefox
- Now that you’ve opened your browser, I’d wait a few seconds until I start trying to execute my script. Do this with a simple:
sleep 5. This simply pauses the program for 5 seconds. You may adjust this based on your system speed.
- Now the browser is fully loaded and ready to go, you need to point it at a URL. In this test, we’ll be searching something on Google.com. Tell the browser to goto Google.com with:
- Now you’ve sent a request to the target site, you need to wait for it to load. I’d give Google around 3 seconds to load, but you can customize this based on your network speed:
- Now you need to locate the exact fields you want to target in your experiment. I’d reccomend you stick with element IDs, but you can find elements with many different tags(types, names, etc.) I want to search for “dogs” on Google. You need to have the broswer click the search field and enter, “dogs.” To find the field ID, you need to head into your regular browser, right click the search bar, inspect, and find a tag you can identify it by. In Google’s case, I’ll be using the name which is, “q.”
- Tell your browser to click q and enter dog with:
browser.text_field(name: 'q').set "dog"Now that you’ve entered your search query, you need to submit your query.
- On Google, you can simply press enter to submit your search. Send the entery key with
Congrats! You can now search Google. Now just finish up the script!
sleep 20so they window stays open for 20 seconds.
browser.closeto close the browser window and finally conclude the script.
By the end of these steps, you should have:
require 'watir' browser = Watir::Browser.new :firefox sleep 5 browser.goto 'https://google.com' sleep 3 browser.text_field(name: 'q').set "dog" browser.send_keys :enter sleep 20 browser.close
This will search Google for dog pictures and leave them up for 20 seconds!
Now, I’ll give a cheat sheet for selecting different types of fields
browser.text_field(name: 'zipcode').set "58517"
Enjoy automating websites!
If you need help, contact me on Discord. I’m Terminal in the Tech Haven Discord.