我遇到了一个棘手的选择困难,它不能使用常用的Selenium api方法。所以,我必须使用Javascript执行器。我到目前为止,无法从下拉列表中正确选择选项=从哪里来?什么目的地?
使用以下代码,当我点击“搜索”时,页面似乎会刷新。也许,传递给JS的css选择器是错误的?
正在测试的网站是:https://club18-30.com/club18-30
private String whereFromText = "LGW"
private String whereToText = "IBZ"
public void setDepartureAirport(String whereFromText)
selectOption(whereFromText);
}
public void setDestinationAirport(String whereToText) {
selectOption(whereToText);
}
public void submitSearchRequest() throws InterruptedException {
By searchButtonLocator = By.xpath(searchButtonLocatorPath);
click(searchButtonLocator);
By searchResultsLocator = By.xpath(searchResultsLocatorPath);
waitForIsDisplayed(searchResultsLocator, 180);
}
public void selectOption(String option) {
String script =
"function selectOption(s) {\r\n" +
" var sel = document.querySelector('.custom-select-options');\r\n" +
" for (var i = 0; i < sel.options.length; i++)\r\n" +
" {\r\n" +
" if (sel.options[i].text.indexOf(s) > -1)\r\n" +
" {\r\n" +
" sel.options[i].selected = true;\r\n" +
" break;\r\n" +
" }\r\n" +
" }\r\n" +
"}\r\n" +
"return selectOption('" + option + "');";
javaScriptExecutor(script);
}
答案 0 :(得分:0)
除了CssSelector表达式之外,您的JavaScript几乎是正确的。目的地机场应为".destinationAirport .custom-select"
,抵达机场应为".arrivalAirport .custom-select"
。但是,我已尝试使用js,但点击提交按钮时应用显示错误。因此,您可能需要单击并选择GUI上的值。请参阅以下代码:
String destination = "Glasgow - Scotland (GLA) United Kingdom";
String arrival = "Ibiza - Balearic Islands (IBZ) Spain";
driver.findElement(By.cssSelector(".destinationAirport .custom-select")).click();
driver.findElement(By.xpath("//*[contains(@class,'destinationAirport')]//li[text()='" + destination + "']")).click();
driver.findElement(By.cssSelector(".arrivalAirport .custom-select")).click();
driver.findElement(By.xpath("//*[contains(@class,'arrivalAirport')]//li[text()='" + arrival + "']")).click();
driver.findElement(By.cssSelector(".searchButton")).click();