Driver
|
You will need internet access if you want to follow examples in this chapter. All examples in this chapter are tried on Mac OS X 10.8.5, Firefox 27.0.1, Ruby 2.1.0p0 and selenium-webdriver 2.40.0 but everything should work on all supported platforms. If you are not familiar with Command-line interface or IRB, see Command-line interface and IRB chapters. |
In this chapter you will learn how to control the browser using Selenium. In Quick Start chapter we have touched two important part of Selenium API, driver and element. In this chapter we will focus on the driver. The chapter will not cover the entire driver API, for more information see Selenium::WebDriver::Driver API documentation.
The first thing you have to do is to open the browser. According to the documentation, currently supported browsers are Firefox, Internet Explorer, Chrome, Android, iPhone, Opera, PhantomJS, Safari and remote browser. Let’s focus on desktop drivers for now. See Mobile chapter on how to drive mobile browsers and Selenium in the Cloud chapter on how to driver remote browsers. How to set up everything is explained in detail in Installation chapter.
| Browser | Symbol | Shortcut |
|---|---|---|
| Chrome | :chrome | |
| Firefox | :firefox | :ff |
| Internet Explorer | :internet_explorer | :ie |
| Opera | :opera | |
| PhantomJS | :phantomjs | |
| Safari | :safari |
How to start a browser
Open Firefox:
1 $ irb
2
3 > require "selenium-webdriver"
4 => true
5
6 > browser = Selenium::WebDriver.for :firefox
7 => #<Selenium::WebDriver::Driver:0x..
8 f8698791d2bff9778 browser=:firefox>
or
1 > browser = Selenium::WebDriver.for :ff
2 => #<Selenium::WebDriver::Driver:...
3 browser=:firefox>
If you want to drive a different browser, just replace :firefox with another symbol.
Let’s try a few interesting methods. get opens a page:
1 > browser.get "http://google.com"
2 => ""
current_url returns page URL:
1 > browser.current_url
2 => "https://www.google.hr/"
title returns page title:
1 > browser.title
2 => "Google"
close closes the current window or the entire browser if there is only one window open.
When you are done with the browser, close it:
1 > browser.close
2 => ""
If you want to close multiple browser windows at once, use quit:
1 > browser.quit
2 => nil
Create a Ruby file from the above IRB session and save it as driver.rb. Of course, add a p in front of a few commands, so the script outputs something.
1 require "selenium-webdriver"
2 browser = Selenium::WebDriver.for :firefox
3 browser.get "http://google.com"
4 p browser.current_url
5 p browser.title
6 browser.close
7 browser.quit
Run the file:
1 $ ruby driver.rb
2 "https://www.google.hr/"
3 "Google"