Sirisha Anupindi
Sirisha Anupindi

Reputation: 33

How to select options provided in a textbox using Selenium

Link: http://www.bbc.com/weather/

Scenario: Type "reading" on the find a forecast text box. This shows 2 options. How do I select one option using Selenium WebDriver?

I am using the following command to type "reading"

driver.findElement(By.id("locator-form-search")).sendKeys("Reading");

Upvotes: 1

Views: 526

Answers (2)

Sirisha Anupindi
Sirisha Anupindi

Reputation: 33

I added explict wait as you suggested and this worked with a small change in the css path. This is what I did:

WebElement suggestedList = new WebDriverWait(driver, 15)
            .until(ExpectedConditions.elementToBeClickable(By
                    .cssSelector("div[class='locator-suggestions locator-suggestions-default'] >ul >li:nth-of-type(1)")));
    driver.findElement(
            By.cssSelector("div[class='locator-suggestions locator-suggestions-default'] >ul >li:nth-of-type(1)"))
            .click();

Upvotes: 2

AGill
AGill

Reputation: 788

Use the following locator to click on the first element (first suggestion displayed after typing):

driver.findElement(By.cssSelector("div[class='locator-suggestions locator-suggestions-default'] li:nth-child(1)")).click();

Similarly you can click on the other element by changing the locator. For example to select the second element:

driver.findElement(By.cssSelector("div[class='locator-suggestions locator-suggestions-default'] li:nth-child(2)")).click();

Just to add here, you may need to wait for the elements/suggestions (which you're trying to select) to be visible, before trying to click on those. Use/search for a appropriate wait method for your testing. So,

  • first you need to type "reading" in the field as you are doing by using driver.findElement(By.cssSelector("input#locator-form-search")).sendKeys("Reading");
  • then wait for element to be visible
  • Then try the above mentioned code to select the desired element.

Hope this helps.

Upvotes: 0

Related Questions