Thursday, October 25, 2012

How to select an item in Listbox using Selenium Webdriver





There are many ways you can do this.

Below are my best ways to select a list item from a listbox:

Option 1:
//First find the Listbox element as WebElement.
WebElement o_Item= driver.findElement(By.id("uw_flight_origin_input_d"));
//Then select the list item from the WebElement
o_Item.findElement(By.xpath("//option[contains(text(),'" + nameYouWant + "')]")).click();

Option 2:
Select menu = new Select(driver.findElement(By.id("uw_flight_origin_input_d"))); menu.selectByVisibleText(nameYouWant);

A complete sample code is here:
import org.openqa.selenium.support.ui.Select;
WebDriver driver=new FirefoxDriver();
driver.get("http://www.expedia.co.in/");
String nameYouWant="Hyderabad";
WebElement o_Item= driver.findElement(By.id("uw_flight_origin_input_d")); o_Item.findElement(By.xpath("//option[contains(text(),'" + nameYouWant + "')]")).click();
/*Select menu = new Select(driver.findElement(By.id("uw_flight_origin_input_d"))); menu.selectByVisibleText(nameYouWant);*/

In the same way how to select a checkbox or radio button based on a value:
Here is a sample HTML code  for an application
<html>
<head></head>
<body>
<form>
<Input type="radio" name="sex" value="male">Male<br>
<Input type="radio" name="sex" value="female">Female<br>
Likes          :<br>
<input type="checkbox" name="likes" value="cars">Cars<br>
<input type="checkbox" name="likes" value="bikes">Bikes<br>
<input type="checkbox" name="likes" value="Movies">Movies<br>
</form>
</body>
</html>

WebDriver driver=new FirefoxDriver();
driver.get("FilePath);
       
driver.findElement(By.xpath("//input[@name='sex' and @value='female']")).click();
       
driver.findElement(By.xpath("//input[@name='likes' and @value='Movies']")).click();

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.