java - 使用 Selenium webdriver 从网页中提取表数据

标签 java html selenium xpath selenium-webdriver

我正在使用 Selenium webdriver(在 Eclipse 中)来自动化 Web 应用程序,但现在的要求是捕获其中一个 html 页面中显示的表格数据。 我尝试了给出的解决方案 here , here和其他一些网站一样,但是我们的网页显示表格的方式似乎有点不同enter image description here

尝试使用 div 类名称作为 String Text = driver.findElements(By.xpath("//div[@class='ag-row ag-row-even ag-row-level- 0']//tr")).get(0).getText();但是它不起作用,抛出索引越界异常

最佳答案

据我所知,您似乎构建了一个自定义表格。 从所附图像中的 HTML 摘录来看,其结构类似于:

<div class="ag-body-container" ...>
    <div class="row_1_class" ...>
        <div class="column_1_class" ...>
        <div class="column_2_class" ...>
        <div class="column_3_class" ...>
        <div class="column_4_class" ...>
        ... etc
    <div class="row_2_class" ...>
        <div class="column_1_class" ...>
        <div class="column_2_class" ...>
        <div class="column_3_class" ...>
        <div class="column_4_class" ...>
        ... etc

但是你的 xPath 假设你有表格行(我猜之后可能还有表格单元格):

By.xpath("//div[@class='ag-row ag-row-even ag-row-level-0']//tr")

导致你的数组为空(有趣的是你没有得到 NoSuchElement 异常,也许你的 html 树中的某个地方有一些 tr 标签)。

现在,我不确定您要从该表中提取什么数据,但您最好的尝试是根据每行的 class 属性获取所有行再次基于 class 属性获取所有列数据(或者您甚至可以使用 col 属性)。

编辑: 要获取所有元素,您可以获取所有行,然后为每行获取所有列数据:

//Get all the rows from the table
List<WebElement> rows = driver.findElements(By.xpath("//div[contains(@class, 'ag-row')));

//Initialize a new array list to store the text
List<String> tableData = new ArrayList<String>();

//For each row, get the column data and store into the tableData object
for (int i=0; i < rows.size(); i++) {
    //Since you also have some span tags inside (and maybe something else)
    //we first get the div columns
    WebElement tableCell = rows.get(i).findElements(By.xpath("//div[contains(@class, 'ag-cell')]"));
    tableData.add(tableCell.get(0).getText());
}

您还可以将数据存储到双向数组(或任何此类数组)中,然后根据行号和列号位置访问数据。

关于java - 使用 Selenium webdriver 从网页中提取表数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34035861/

相关文章:

java - 文件对象是否支持所有文件(键盘、目录、文件等)?

java - 如何将以对象为键的 map 列表转换为 map ?

javascript - 如何在D3中对齐文本和标签

java - 使用或不使用 docker 进行 Selenium 测试

java - 如何使用 Jenkins 将 Selenium 测试重定向到远程机器

java - 如何通过Selenium访问框架内的嵌套html

java - 坚持理解递归

html - 我怎样才能让这些单选按钮并排放置

jquery - 为什么不重置高度

java - 通过 Java 和 Selenium 启动 Internet Explorer 时出现 "OsProcess checkForError : CreateProcess error=193, %1 is not a valid Win32 application"