首页 > 解决方案 > How to handle Auto suggestion in selenium?

问题描述

/I want to select Mumbai as source and Delhi as destination from autosuggestion on cleartrip website. I have written below code. Here source is getting handled properly but on destination, autosuggestion list is displayed but nothing get selected from the list. Could someone please help me out/

String baseurl = "https://www.cleartrip.com/";
driver.get(baseurl);
String title = driver.getTitle();
System.out.println(title);
WebDriverWait wait=new WebDriverWait(driver, 20);
WebElement flighttab = driver.findElement(By.linkText("Flights"));
flighttab.click();
Thread.sleep(5000);
WebElement roundtrip_radio_button = driver.findElement(By.id("RoundTrip"));
roundtrip_radio_button.click();
WebElement from = driver.findElement(By.xpath(".//*[@id='FromTag']"));
WebElement to =driver.findElement(By.xpath(".//*[@id='ToTag']"));
from.clear();
from.sendKeys("Mumbai");
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//ul/li[@class='list']")));
driver.findElement(By.xpath("//ul/li[@class='list']")).click();
to.clear();
to.sendKeys("Delhi");
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//ul/li[@class='list']")));
driver.findElement(By.xpath("//ul/li[@class='list']")).click();

标签: selenium

解决方案


The xpath that you are using is incorrect. I am providing you the correct xpath and an alternate way to click on the auto-completer (by using className), you can use either of them, both will work fine. And as the wait.until method returns the element, you can directly perform the click on it, which would result in one atleast less operation/scraping on the page.

Autocompleter Correct Xpath:

wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//a[@class='uiSelected']"))).click();  

Autocompleter by className:

wait.until(ExpectedConditions.visibilityOfElementLocated(By.className("uiSelected"))).click();  

推荐阅读