如何始终选择列表中的最后一项

时间:2015-02-10 16:00:09

标签: selenium selenium-webdriver

我需要选择DYNAMIC列表中的最后一项。以下是我的脚本。谢谢!

WebElement selectElement = driver.findElement(By.name("siteKey"));
Select select = new Select(selectElement);
//select.selectByVisibleText("last item");
//select.selectByIndex(0);
//select.selectByValue("value");

请参阅下面的HTML页面。如果我能为您提供任何其他信息,请告诉我。谢谢!

<div id="overview_form">
<ol>

<li>
<span>1.</span>
<label class="input_label" for="sites">Sites*</label>
<div class="select2-container select2-container-active select2-dropdown-    open" id="s2id_autogen1" style="width: 500px;">
<a tabindex="-1" class="select2-choice" onclick="return false;"     href="javascript:void(0)">   
<span>www.roger.com_20150210075155</span>
<abbr style="display:none;" class="select2-search-choice-close"></abbr>   
<div><b></b></div></a>
<input type="text" class="select2-focusser select2-offscreen" disabled="disabled">
</div>
<select style=" size="1" name="siteKey" class="select2-offscreen" tabindex="-1">

<option value="30518">www.roger.com_20150209191817</option>
<option value="30520">www.roger.com_20150209192123</option>
<option value="30522">www.roger.com_20150209192351</option>
<option value="30524">www.roger.com_20150209192910</option>
<option value="30528">www.roger.com_20150209193425</option>
<option value="30529">www.roger.com_20150209193801</option>
<option value="30531">www.roger.com_20150209194009</option>
<option value="30546">www.roger.com_20150210074133</option>
<option value="30548">www.roger.com_20150210074359</option>
<option value="30550">www.roger.com_20150210075155</option></select>

</li>
</ol>
</div>

3 个答案:

答案 0 :(得分:3)

如下:

WebElement selectElement = driver.findElement(By.name("siteKey"));
Select select = new Select(selectElement);
select.selectByIndex(select.getOptions().size()-1);

答案 1 :(得分:1)

您可以使用getOptions(),它将返回一个列表,然后获取列表的大小

Select select = new Select(driver.findElement(By.id("siteKey")));
List<WebElement> l = select.getOptions(); 
int numElements = l.size();
select.selectByIndex(munElements);

希望这有帮助

答案 2 :(得分:0)

我尝试了以下方式,并且它正在工作......也许这会对你有所帮助。

    WebDriver driver = new FirefoxDriver();
    driver.get("http://www.echoecho.com/htmlforms11.htm");
    Thread.sleep(100l);
    driver.findElement(By.xpath("//select[@name='dropdownmenu']")).click();
    Thread.sleep(100l);
    WebElement element = driver.findElement(By.xpath("//select[@name='dropdownmenu']"));
    List<WebElement> elements = element.findElements(By.tagName("option"));
    System.out.println(elements.get(elements.size() - 1).getText());