Nik_stack
Nik_stack

Reputation: 213

Finding Web-Element with Selenium Webdriver

I am new to Test Automation and here is the example I found to get started.

require 'rubygems'
require 'selenium-webdriver'

driver = Selenium::WebDriver.for :firefox
driver.get "http://google.com"

element = driver.find_element :name => "q"
#element = driver.find_element :xpath => "//*[@id='gbq2']"
element.send_keys "Cheese!"
element.submit

puts "Page title is #{driver.title}"

wait = Selenium::WebDriver::Wait.new(:timeout => 10)
wait.until {driver.title.downcase.start_with? "cheese!"}

puts "Page title is #{driver.title}"
driver.quit

From the limited amount of information, I know that it is finding the element by its name: 1. How do I know that the name of the element is 'q'?
2. If I have to find an element by X-path, why doesnt it work for the following command?

#element = driver.find_element :xpath => "//*[@id='gbq2']"

Upvotes: 1

Views: 1839

Answers (2)

David Ambler
David Ambler

Reputation: 153

If you want to find an element by name, you can do it this way:

element = driver.find_element :css, 'input[name=q]'

That should do the trick.

Upvotes: 0

7stud
7stud

Reputation: 48599

  1. How do I know that the name of the element is 'q'?

4.html:

<!DOCTYPE html>
<html>
<head>
<title>Testing</title>
<meta charset="UTF-8">
</head>
<body>
  <div name="d1">Hello</div>
  <div name="d2">World</div>
</body>
</html>

ruby program:

require 'selenium-webdriver'

driver = Selenium::WebDriver.for :firefox
driver.get "http:localhost:8080/4.htm"

element = driver.find_element :name => "d1"
puts element.text

--output:--
Hello

How does the program know to look for an element whose name is "d1"? Because I wrote the program, and I decided I wanted to find the text of the element whose name attribute was equal to "d1", so that's what I wrote in the code. If the program looked for an element whose name was 'q' on that html page, what do you think would happen?

If you look through the source code of http://www.google.com, there is an html element whose name is 'q', and whoever wrote the ruby selenium web driver example that you posted wanted to fetch that element in order to manipulate it.

Upvotes: 2

Related Questions