Selenium WebDriver with Ruby: Examples and General Reference
Last updated:select an option from a dropdownlist / select input
In order to select the option that reads "some text"
from the dropdownlist whose id is my-dropdown:
DRIVER = Selenium::WebDriver.for :firefox
option = Selenium::WebDriver::Support::Select.new(DRIVER.find_element(:css => "#my-dropdown"))
option.select_by(:text, "some text")
wait for a page to load
Wait for a page to load. If it takes more than the time passed as argument (the timeout) for the page to become available, an error is raised.
DRIVER = Selenium::WebDriver.for :firefox
wait = Selenium::WebDriver::Wait.new(:timeout => 3)
wait.until { DRIVER.current_url=='http://some_url'}
click ok / accept on an alert dialog
DRIVER = Selenium::WebDriver.for :firefox
DRIVER.switch_to.alert.accept
find out whether an element is present on the page
use function find_elements
rather than find_element
because if an element isn't found the first function raises an error:
DRIVER = Selenium::WebDriver.for :firefox
if DRIVER.find_elements(:css,"your selector").empty?
# nothing here
else
# element found
end
run javascript
DRIVER = Selenium::WebDriver.for :firefox
result = DRIVER.execute_script('return "foo"')
# result now holds "foo"
result2 = DRIVER.execute_script('$("#my_text_input").val());
# result2 now holds whatever text was in your text input
find an element within another element
In other words, run a scoped query in an Element (you want to find all <p>
elements within your #my-div
div):
DRIVER = Selenium::WebDriver.for :firefox
outer_div = DRIVER.find_element(:css,"#my-div")
p_elements = outer_div.find_elements(:css,"p")
# you can run find_element / find_elements on a single Element!