【发布时间】:2015-08-06 19:08:04
【问题描述】:
我正在尝试从两个 Ajax 下拉字段中选择一个特定值。但是两个 ajax 值容器都具有相同的类名“ac_results”。因此,只有第一个 ajax 下拉字段中的值被选中,它没有识别第二个 ajax 下拉值。请在这方面帮助我。 HTML 代码:
<div class="ac_results" style="display: none; position: absolute; width: 150px; top: 225px; left: 489.317px;">
<ul style="max-height: 180px; overflow: auto;">
<li class="ac_even"></li>
<li class="ac_odd"></li>
<li class="ac_even"></li>
<li class="ac_odd"></li>
<li class="ac_even"></li>
<li class="ac_odd"></li>
<li class="ac_even"></li>
</ul>
</div>
<div class="ac_results" style="display: none; position: absolute; width: 150px; top: 225px; left: 781.733px;">
<ul style="max-height: 180px; overflow: auto;">
<li class="ac_even"></li>
<li class="ac_odd"></li>
<li class="ac_even"></li>
<li class="ac_odd"></li>
</ul>
代码:
//get the from field
WebElement fromCity = driver.findElement(By.id("txtStationFrom"));
//Enter the value into the from city field
fromCity.sendKeys("ban");
//wait for some time
Thread.sleep(2000);
//get the ajax container having values
WebElement ajaxContainer1 = driver.findElement(By.className("ac_results"));
WebElement ajaxHolder1 = ajaxContainer1.findElement(By.tagName("ul"));
//Values in the container
List<WebElement> ajaxValues1 = ajaxHolder1.findElements(By.tagName("li"));
for (WebElement value1 : ajaxValues1) {
if(value1.getText().equals("BANGALORE CY JN- SBC")){
value1.click();
break;
}
}
//Get the to city field
WebElement toCity = driver.findElement(By.id("txtStationTo"));
//pass the value to the field
toCity.sendKeys("sub");
//Wait for some time
Thread.sleep(2000);
//get the container of the ajax toCity
WebElement ajaxContainer2 = driver.findElement(By.className("ac_results"));
WebElement ajaxHolder2 = ajaxContainer2.findElement(By.tagName("ul"));
List<WebElement> ajaxValues2 = ajaxHolder2.findElements(By.tagName("li"));
for (WebElement value2 : ajaxValues2) {
if(value2.getText().equals("SUBRAHMANYA ROAD- SBHR")){
value2.click();
break;
}
}
【问题讨论】:
-
您尝试过使用 xpath 吗?
-
@HelpingHands 不,我没有使用 xpath。
-
那你应该试试。
-
您共享的 HTML 不是实际的下拉列表,您可能正在使用一些插件/框架,它会从中生成下拉列表。
-
@HelpingHands:我尝试了 xpath,但出现“NoSuchElementException”错误。
标签: java ajax selenium drop-down-menu selenium-webdriver