简体   繁体   中英

How to select a value from a lookup field using selenium webdriver

I am trying to test a trip planner website using selenium webdriver.

Say for eg I am testing cleartrip.com.
How to select a city from the lookup field using selenium?

For instance, I have to select the source city.
If I type DE, it gives me options like "Delhi, "Dehradun" based on what I have typed and out of these options, I have to select say Delhi.

How to achieve it using Selenium? Kindly suggest.
I am new to selenium and any help would be appreciated.

This code works for me

        WebDriver driver = new FirefoxDriver();
        driver.get("http://www.cleartrip.com/");

        WebElement From = driver.findElement(By.id("FromTag"));

        From.sendKeys("Del");

        WebElement autoComplete = driver.findElement(By.id("ui-id-1"));

        try{
            (new WebDriverWait(driver, 5/*sec*/)).
                    until(ExpectedConditions.presenceOfElementLocated((By.cssSelector("li.list"))));             }
        catch(org.openqa.selenium.TimeoutException e){
            System.out.println(e.getMessage());
        }

        List<WebElement> autoCompleteList = autoComplete.findElements(By.className("list"));

        if(autoCompleteList.size()==0) {
            System.out.println("autoComplete list NOT found");
        }
        else {
            System.out.println("autoComplete list Found with elements: "+autoCompleteList.size());
        }

        for (WebElement ac: autoCompleteList){
            if(ac.getText().contains("Delhi")){  
                ac.click();
                break;
            }
        }
        driver.close();

Please note this is just example, please improve the code adding verifications that objects not a null, remove the hardcoded strings, etc.

You can simply achieve it by putting up some wait and then clicking the desired city, like:

public CurrentPage selectFrom(String cityCode, String cityName){
    driver.findElement(By.id("FromTag")).sendKeys(cityCode);;
    new WebDriverWait(driver, 5).until(
        ExpectedConditions.elementToBeClickable(
            By.xpath(".//*[@id='ui-id-1']//a[contains(.,'" + cityName + "')]")))
                .click();
    return this;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM