如何从填充的选项中选择元素

时间:2013-05-13 06:57:47

标签: selenium-webdriver

我需要用Selenium-Webdriver编写一个脚本。我陷入了需要在文本框中输入文本(例如:"tt")并填充列表(隐藏值)的情况。我们需要从填充的列表中选择一个选项。 (就像我们在“Google”搜索中所做的那样)。

<div class="select2-search">
  <input type="text" autocomplete="off" class="select2-input tabindex="-1" style>
</div>
<ul class="select2-results">
<li class="select2-results-dept-0 select2-result select2-result-selectable select2-new">
  <div class="select2-result-label">
    <span class="select2-match">et</span>
  </div>
</li>
<li class="select2-results-dept-0 select2-result select2-result-selectable select2-highlighted">
  <div class="select2-result-label">"Secr"
    <span class="select2-match">et</span>"ary"
  </div>
</li>
<ul>

1 个答案:

答案 0 :(得分:0)

所以我会写一些代码来帮助你。

我使用www.google.com作为例子。

WebElement inputElement = driver.findElement(By.id("gbqfq")); // get the input
inputElement.sendKeys("zyzz"); // you want to search him on internet ;)
// get all suggestions in a list
List<WebElement> suggestionList = driver.findElements(By.CssSelector(".gsq_a table tbody tr td:first-of-type span"));

要选择一个选项,您有两个选择:第一个:

// you get a random option and click on it
suggestionList.get(1).click();

// you only want to click on the link that contains that.
for(WebElement elem: suggestionList)
{
  String text = elem.getText();
  if(text.equals("zyzz motivation"))
  elem.click();
}