如何遍历List <webelement> </webelement>

时间:2014-10-21 23:52:34

标签: java selenium xpath selenium-webdriver gettext

我需要帮助获取List<WebElement>的xpath以及如何遍历它并选择等于&#34; 2014的好处&#34;的链接文本。来自以下代码。

<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>

我正在尝试使用以下代码:

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();
}

2 个答案:

答案 0 :(得分:4)

你可以做点像......

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
    }
}

答案 1 :(得分:3)

通过链接文本查找链接将更加可靠,可读和明确:

WebElement element = Driver.findElement(By.linkText("2014 Benefits"));