Java 如何遍历 List<WebElement>
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26498299/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to loop through List<WebElement>
提问by venkatkamraj
I need help in getting the xpath for List<WebElement>
and how to loop through it and select the link text which is equals to "2014 Benefits" from the below code.
我需要帮助来获取 xpathList<WebElement>
以及如何遍历它并从下面的代码中选择等于“2014 Benefits”的链接文本。
<tbody id="tblPriorEventsBody">
<tr>
<td>01/01/2014</td>
<td>
<a class="openEvent aActive" onclick='DisplayEventYearElections("dvCurrentElections","2014","Benefits For 01/01/2014 Open Enrollment ( 2014 ) ","2e82be0c-f280-4502-9d98-cf995450442c");' href="#">
2014 Benefits
</a>
<input id="hfOpenEventDefinationId" type="hidden" value="b991cf84-f197-413f-a3fb-21c5a1c0d70a"></input>
</td>
<td>N/A</td>
<td>N/A</td>
</tr>
<tr>...</tr> // Each tr contains a link
<tr>...</tr>
<tr>...</tr>
<tr>...</tr>
<tr>...</tr>
</tbody>
I am trying with the below code:
我正在尝试使用以下代码:
List <WebElement> options = Driver.findElements(By.xpath("//tbody[@id='tblOpenEventsBody']//tr/a"));
System.out.println(" CLASS Elements size " + options.size());
for (WebElement option : options) {
String Str = "2014 Benefits" // based on string text match I want to select
if("Str".equals(option.getText())){
option.click();
break();
}
采纳答案by bcar
You could do something like...
你可以做一些像...
List<WebElement> links = driver.find elements(By.cssSelector('#tblPriorEventsBody td a'));
Iterator<WebElement> iter = links.iterator();
while(iter.hasNext()) {
WebElement we = iter.next();
if (we.text.equals("whatever") {
we.click;
// do something in else perhaps
}
}
回答by alecxe
Finding the link by link textwould be more reliable, readable and explicit:
通过链接文本查找链接会更可靠、可读和明确:
WebElement element = Driver.findElement(By.linkText("2014 Benefits"));