I am trying to get familiar with the new ruby selenium-webdriver as it appears more intuitive mostly than the previous version of selenium and the ruby driver that went with
The easiest way I found was:
select_elem.find_element(:css, "option[value='some_value']").click
Full disclosure here: I have absolutely no working knowledge of Ruby.
However, I'm pretty good with Selenium so I think I can help. I think what you're looking for is the select method. If ruby is anything like the other drivers you can use the select method to tell one of the options it is selected.
In pseudocode/java terms it would look something like this
WebElement select = driver.findElement(By.name("select"));
List<WebElement> options = select.findElements(By.tagName("option"));
for(WebElement option : options){
if(option.getText().equals("Name you want")) {
option.click();
break;
}
}
The Select object you have above is actually in a special Support package. It only exists for Java and .Net at the moment (Jan 2011)
require "selenium-webdriver"
webdriver = Selenium::WebDriver.for :firefox
driver.navigate.to url
dropdown = webdriver.find_element(:id,dropdownid)
return nil if dropdown.nil?
selected = dropdown.find_elements(:tag_name,"option").detect { |option| option.attribute('text').eql? value}
if selected.nil? then
puts "Can't find value in dropdown list"
else
selected.click
end
In my case this is only one working sample.
Ruby Code with Example:
require "selenium-webdriver"
driver = Selenium::WebDriver.for :ie
driver.navigate.to "http://google.com"
a=driver.find_element(:link,'Advanced search')
a.click
a=driver.find_element(:name,'num')
options=a.find_elements(:tag_name=>"option")
options.each do |g|
if g.text == "20 results"
g.click
break
end
end
You can use XPath to avoid looping:
String nameYouWant = "Name you want";
WebElement select = driver.findElement(By.id(id));
WebElement option =
select.findElement(By.xpath("//option[contains(text(),'" + nameYouWant + "')]"));
option.click();
or
WebElement option =
select.findElement(By.xpath("//option[text()='" + nameYouWant + "']"));
Please note that none of the above will work anymore. Element#select
and Element#toggle
have been deprecated. You need to do something like:
my_select.click
my_select.find_elements( :tag_name => "option" ).find do |option|
option.text == value
end.click