Watir and Ruby: Drive a Browser Step by Step
Watir gives Ruby developers a readable way to control a real browser: open a page, find elements, type into fields, click buttons, run JavaScript, and capture screenshots. This guide walks through a complete Wikipedia search flow so you can see each method in context and know what to check when a step fails.
What browser automation covers
Browser automation means letting a program perform actions in a browser that a person would otherwise repeat by hand. Typical jobs include entering data, pulling data from pages, uploading files, and running the same checks across several browsers or operating systems.
A common case is a site that publishes useful information but offers no API. A browser-driven script can open the page, read the visible content, and hand the result to your own code. The same approach works for filling forms at volume and for testing whether links, layouts, and response times behave consistently across Chrome, Firefox, Edge, Safari, or Internet Explorer.
What Watir is and how it relates to Selenium
Watir stands for Web Application Testing In Ruby and is pronounced like "water." It is a set of open-source Ruby libraries that wrap Selenium, adding a Ruby-friendly interface and some conveniences on top. If you already know Selenium concepts, the mental model carries over; Watir changes how you express the same browser actions in Ruby.
The walkthrough below uses Wikipedia as a safe public target. The script opens a browser, visits the Wikipedia landing page, follows the English-language link, types a search term, submits it, prints some page data, raises an alert through JavaScript, saves a screenshot, and closes the browser.
Install the gems
You need Ruby installed and some comfort with the command line and IRB. First check whether the watir and webdrivers gems are already present by listing your gems:
gem list
If either is missing, install it:
gem install watir gem install webdrivers
Then start IRB on Linux or macOS, or an Interactive Ruby session on Windows. You can paste the snippets one line at a time to watch the browser react, or save them as a script and run the whole flow.
Load the libraries
At the top of your script, require both gems:
require 'watir' require 'webdrivers'
Watir supplies the automation API. The webdrivers gem handles the browser driver integration so you do not have to fetch a separate driver package for each browser you want to use.
Launch a browser and open a page
Create a browser instance and point it at a URL:
browser = Watir::Browser.new browser.goto("wikipedia.org")
Watir::Browser.new starts a browser session; goto loads the address you pass. Chrome is the default. To use another supported browser, pass it as an option, for example Watir::Browser.new :firefox. Firefox, Internet Explorer, Edge, and Safari are listed as compatible. When Chrome is under automation, it displays a notice that it is being controlled by automated test software.
Find elements and read page data
Watir exposes collections and single-element lookups. The links method returns every link on the page, while link returns only the first. Chaining links to Ruby's count gives a quick data point:
puts browser.links.count
To follow the English-language link on the Wikipedia landing page, target the element by its class and attributes, confirm it is present, then click it:
english_link = browser.div(class: "lang1") english_link.present? english_link.click puts browser.url
Use your browser's developer tools to inspect the classes and attributes you need. Calling url on the browser object tells you which page you are on, which is useful for confirming that a click actually navigated.
Extract text from a specific element
The element method accepts selectors such as an id. To read the article count on the page:
puts browser.element(id: 'articlecount').text.strip
Once the element is located, text returns its text content and strip removes trailing newlines. If the selector does not match anything, the lookup fails rather than returning an empty string, so verify the id in the page source before assuming the extraction logic is wrong.
Locate a text field
Form fields have their own lookup method. text_field works like element but targets input fields:
search_box = browser.text_field(class: "vector-search-box-input")
The result is stored in a variable you can reuse. The class name above is specific to the page being automated, so inspect the field you actually need and substitute its selector.
Set text and wait for readiness
The set method fills a field. Pair it with wait_until so the action only runs once the field is ready:
search_box.wait_until(&:present?).set("sailing yachts")
This matters because page loads are not instant. Calling set, or any other action, on an element that has not loaded or is disabled raises an error. wait_until takes a block or proc and repeats it until it returns true; here the proc is present?, which checks that the element exists and is usable.
wait_until belongs to the Waitable module, which is included in Element, Alert, Window, Browser, ElementCollection, and WindowCollection. Its sibling wait_while keeps evaluating until the condition becomes false. Both stop after a default thirty-second timeout, which you can adjust.
Run JavaScript in the page
execute_script runs JavaScript in the current page. The example below opens an alert with a custom message, waits until that text appears, pauses briefly so a human can see it, and dismisses it:
browser.execute_script("alert('On the page for sailing yachts !')") browser.alert.wait_until { |a| a.text == "On the page for sailing yachts !" } sleep 3 browser.alert.ok
The wait_until call synchronizes the script with the page, checking the alert text before proceeding. alert.ok closes the dialog. The sleep call is optional and exists only to keep the modal visible long enough to observe; in production automation, the Waitable methods are generally the better tool.
Save a screenshot and close the browser
Capture the current page and shut the session down:
browser.screenshot.save("./sailboats_screenshot.png") browser.close
The screenshot method captures the page, save writes it to the path you give, and close ends the browser session. At this point the script has opened a browser, navigated, searched, extracted data, run JavaScript, and saved an image.
Decision checklist for each step
Use this checklist when writing or debugging a Watir flow:
- Opening a page: use Watir::Browser.new followed by goto with the full URL.
- Reading a list: use links when you need all links, link when you only need the first.
- Targeting one element: use element with an id or selector; use div, button, or text_field when the element type is known.
- Filling a field: use text_field to locate it, wait_until(&:present?) to confirm readiness, then set to write the value.
- Submitting: locate the button by a stable attribute such as value, then click.
- Running page scripts: use execute_script; use alert.wait_until when a dialog must appear before you act on it.
- Capturing output: use screenshot.save with a file path, then close the browser.
When something fails, separate the causes: a selector that matches nothing is a lookup problem; a selector that matches but acts too early is a timing problem; an action on a disabled element is a state problem. Adding a wait will not fix a wrong selector, and changing the selector will not fix a missing wait.
Field and control map for the example flow
The table below maps each action in the Wikipedia example to the Watir method and selector used, so you can adapt the pattern to another site.
Where to go next
The methods above cover the core loop of browser automation: open, locate, act, wait, capture, close. Watir also supports more advanced scraping and can be paired with test frameworks such as minitest and rspec for automated headless testing. The official Watir guides and the Ruby-focused references linked from this page go deeper into those areas.
| Step | Watir method | Selector or input | Purpose |
|---|---|---|---|
| Open browser | Watir::Browser.new | browser option (default Chrome) | Start a browser session |
| Navigate | goto | URL string | Load a page |
| Count links | links.count | none | Read how many links are present |
| Target language link | div | class: "lang1" | Select the English-language link |
| Check presence | present? | none | Confirm the element exists |
| Click link | click | none | Follow the link |
| Read current URL | url | none | Confirm navigation |
| Extract text | element | id: 'articlecount' | Read the article count |
| Locate search field | text_field | class: "vector-search-box-input" | Target the search input |
| Wait for field | wait_until | &:present? | Ensure the field is ready |
| Fill field | set | "sailing yachts" | Enter the search term |
| Locate button | button | value: "Go" | Target the submit button |
| Click button | click | none | Submit the search |
| Run JavaScript | execute_script | alert string | Open an alert dialog |
| Wait for alert | alert.wait_until | text comparison | Synchronize with the dialog |
| Dismiss alert | alert.ok | none | Close the dialog |
| Save screenshot | screenshot.save | file path | Capture the page |
| Close browser | close | none | End the session |
Selectors reflect the Wikipedia page structure at the time of the original walkthrough; verify current class names and ids before reuse.
Frequently asked questions
Is Watir a replacement for Selenium?
No. Watir wraps Selenium and adds a Ruby-friendly layer on top. You still rely on Selenium's browser-driving foundation underneath.
Which browser does Watir open by default?
Chrome. You can choose another supported browser by passing it as an option, for example Watir::Browser.new :firefox. Firefox, Internet Explorer, Edge, and Safari are listed as compatible.
How long do wait_until and wait_while wait?
Both have a default thirty-second timeout. You can adjust it when a page or element needs more or less time.
Why does an action fail even though the element is on the page?
The element may not be loaded or enabled yet. Calling set or another action too early raises an error. Use wait_until with a condition such as present? to delay the action until the element is ready. If the selector itself is wrong, a wait will not help.
Should I use sleep in automation scripts?
Usually not. sleep pauses the thread for a fixed time regardless of page state. The Waitable methods are generally more efficient. In the example, sleep is included only so a person can see the alert before it closes.