As we have already seen that the Selenium WebDriver predefined method sendKeys( ) is used for entering text into the text fields. But we can also use this method for selecting a list item from the drop down list field.
Lets implement the following Test as explained using the comments on the below screenshot:
Lets Implement This:
1. Create a new Java Project say 'WebDriver-Project7' in Eclipse IDE
2. Configure the Project to work with Selenium WebDriver
3. Create a package say 'package7' under the newly created project.
4. Create a Java Class file say 'Class7' under the newly created package as shown below:
1. Write the following code into the newly created Java Class file as shown below and make sure that you resolve all the errors before going to next step:
2. The above code will create a Selenium WebDriver object, Launch a new Firefox Browser session, opens the http://book.theautomatedtester.com/chapter1 page in the Browser window and finally it maximizes the Browser window as shown below:
3. Now lets write Selenium WebDriver code for selecting the list option 'Selenium Grid' from the drop
down field as explained in the Test Description above by following the below steps:
4. Using FireBug options, Inspect the drop down field and identify the locator after observing the below code in the below screenshot:
5. After seeing the above html code in the screenshot, its very clear that we've to identify the drop down field using ID locator i.e. using id=selecttype in this case.
6. Also we've to use the above ID locator in the Selenium WebDriver Command which is used to select the specified list item in the identified drop down list. _driver.findElement(By.id("ID LOCATOR")).sendKeys("List Item Label"); is the syntax we've to use for selecting the list item from the specified locator.
Lets understand the _driver.findElement(By.id("ID LOCATOR")).sendKeys("List Item Label"); syntax by breaking it as below:
7. So after understanding the things in step5 and step6, its very clear that we've to write _driver.findElement(By.id("selecttype")).sendKeys("Selenium Grid"); to select the list item label 'Selenium Grid' under the Drop down field as shown below:
8. Run the Test using JUnit Test as shown below:
9. After the test has run completely, observe that the specified List Item Label got selected in the Dropdown field as shown below:
Watch the below video: