硒2和html表 [英] Selenium 2 and html tables

查看:90
本文介绍了硒2和html表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想知道是否有更好的方法从硒2的表中获取值.我目前在每个TR上使用2 for循环,在每个TD上使用每个TR循环.因此,例如,如果我有一个包含10列的表格行,那么我循环10次并拉出文本值.在我看来,这很笨拙.

Just wondering if there is a better way to get values from a table in selenium 2. I am currently using 2 for loops I loop over each TR and within each TR I loop over all TD. so for example if I have a table row with 10 columns I loop 10 times and pull out the text value. That seems clunky to me.

我的表格行看起来像这样

My table Rows looks like so

<tr id="cTestData" class="odd">
<td class="date_activated">08/31/2011</td>
<td class="date_redeemed"> Not redeemed * </td>
<td class="expiration_date">09/01/2011</td>
<td class="product"> State of Maine </td>
<td class="value">$1.00</td>
<td class="store"> &ndash; &ndash; &ndash; </td>
<td class="offer_details">
</tr>

我想我应该能够为每个表说行,让我得到class = date_activated的TD元素,并让它返回日期.我尝试了几件事,但基于TD类名称= foo

I think I should be able to say for each table Row get me the TD element with class = date_activated and have it return the date. I tried a few things but nothing seemed to work based on TD class name = foo

如果对我的实际代码有帮助的话

If it helps my actual code is

for(WebElement trElement : tr_collection)
        {
            List<WebElement> td_collection=trElement.findElements(By.xpath("td"));
            System.out.println("NUMBER OF COLUMNS="+td_collection.size());
            col_num=1;          
            HashMap actInfo = new HashMap();  // new hashmap for each line inthe result set

            if(!td_collection.isEmpty() && td_collection.size() != 1 ){  
                for(WebElement tdElement : td_collection)
                {
                        System.out.println("Node Name=== " + tdElement.getAttribute("class")); 
                        System.out.println("Node Value=== " + tdElement.getText());
                        actInfo.put(tdElement.getAttribute("class"), tdElement.getText());
                    col_num++;
                }
                masterMap.add(actInfo);
            } // end if

            row_num++;
        }

推荐答案

尝试一下:

driver.findElements(By.xpath("//tr[@class='foo']/td[@class='date_activated']"))

这将返回所有类为date_activated的TD元素,并且其父行的类为foo.然后,您可以遍历元素并使用getText获取日期.这可以从页面的 root 使用.

That will return all the TD elements with the class date_activated with a parent row with class foo. You can then loop through the elements and use getText to get the dates. This works from the root of the page.

如果您想从每个 TR元素中进行操作,请尝试:

If you would like to do it from each TR element, try:

trElement.findElement(By.xpath("./td[@class='date_activated']")).getText()

这篇关于硒2和html表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆