如何识别HTML表格中的单元格(Selenium)

时间:2012-10-09 13:01:20

标签: selenium

我的任务是右键单击并从HTML表格的下拉菜单中选择一个选项。

为此我需要帮助两件事:

  1. 如何使用硒来识别表格内的唯一单元格?

  2. 如何右键单击已识别的单元格?

  3. 此应用程序仅针对IE开发,表格的示例代码如下:

    table id="ctl00_ContentPlaceHolder1_dgvPatientList" class="grid" cellspacing="0" cellpadding="2" border="1" style="width:96%;border-collapse:collapse;" rules="all">
    

    ![这是HTML表格的代码] [1] 谢谢您的帮助。

2 个答案:

答案 0 :(得分:1)

考虑到你的第一次静止, 这里讨论了很多(manipultion with table cells using selenium) 提供的代码(在代码示例中,我们从表的每个单元格中获取文本):

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.ie.InternetExplorerDriver;

public class WebTableExample 
{

    public static void main(String[] args) 
    {
        WebDriver driver = new InternetExplorerDriver();
        driver.get("http://localhost/test/test.html");


        WebElement table_element = driver.findElement(By.id("testTable"));
        List<WebElement> tr_collection=table_element.findElements(By.xpath("id('testTable')/tbody/tr"));

        System.out.println("NUMBER OF ROWS IN THIS TABLE = "+tr_collection.size());
        int row_num,col_num;
        row_num=1;
        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;
            for(WebElement tdElement : td_collection)
            {
                System.out.println("row # "+row_num+", col # "+col_num+ "text="+tdElement.getText());
                col_num++;
            }
            row_num++;
        }    
    }       
}

考虑到你的第二个问题。调查了一点点的解决方法。 其中一种可能性:

selenium.mouseDownRight(locator);
  selenium.mouseUpRight(locator);

另一种方式:

WebElement elem = driver.findElement(By.xpath(".blablabla..")); //the element we want to //right click on
new Actions(driver).contextClick(elem).perform();

其他方式是使用javascript。

因此,您将表格单元格作为webElement。然后你右键单击它。希望它适合你。

答案 1 :(得分:0)

原始问题没有指定语言,因此这可能适用也可能不适用,但是如果您使用 C# 和 .NET 版本的 WebDriver 编写测试,则可以使用 TableDriver 扩展 (https://github.com/jkindwall/TableDriver.NET ) 用于定位表格中的特定单元格。

我不知道原始问题中表格的内容是什么样的,但举一个通用示例,您想从“产品 ID”中的值所在的行中找到“价格”列中的单元格列是“ABC123”,你可以使用这样的东西:

Table table = Table.Create(driver.FindElement(By.Id("ctl00_ContentPlaceHolder1_dgvPatientList")));
TableCell cell = table.FindCell("Product Id=ABC123", "Price");

更新

TableDriver.Java 现已可用。详情请见:https://github.com/jkindwall/TableDriver.Java