简体   繁体   English

Selenium 读取复杂表结构

[英]Selenium read complex table structure

I am using Selenium in my Java project.我在我的 Java 项目中使用 Selenium。 Selenium buys coupons in a test and then wants to see them in the coupon overview. Selenium 在测试中购买优惠券,然后想在优惠券概览中看到它们。 There can be multiple coupon packages there if the user has bought some before.如果用户之前购买了一些优惠券包,那里可以有多个优惠券包。

The table structure on the page looks something like this:页面上的表结构如下所示:

<div>
  <div><div>
    <table>
      <thead></thead>
      <tbody>
        <tr>
        <tr><td>Coupon-Code 1</td><td>Unused</td></tr>
        <tr><td>Coupon-Code 2</td><td>Used</td></tr>
        </tr>
      </tbody>
     </table>
  </div></div>
  <div><div>
    <table>
      <thead></thead>
      <tbody>
        <tr><td>Coupon-Code 1</td><td>Used</td></tr>
        <tr><td>Coupon-Code 2</td><td>Unused</td></tr>
      </tbody>
     </table>
  </div></div>
</div>

I have not yet found a way to read in the coupons.我还没有找到阅读优惠券的方法。 I want to store them in a list, each table of the HTML page should correspond to an entry in the list and contain the coupon codes and their used/unused value.我想将它们存储在一个列表中,HTML 页面的每个表都应该对应于列表中的一个条目,并包含优惠券代码及其使用/未使用的值。

Do you have any idea how I can implement it?你知道我该如何实现它吗?

I have already done some things with我已经做了一些事情

List<WebElement> webElements = driver.findElements(by.tagName("table"));

but here I can't read the entries of the table....但在这里我无法阅读表格的条目....

List<WebElement> webElements = driver.findElements(by.tagName("table"));
WebElement webElementsCoupon = webElements[0].findElement(by.tagName("tr"));

get tr tag from each table and then td, now you get the text using getText()从每个表中获取 tr 标记,然后 td,现在您使用 getText() 获取文本

You need to first identify table element and then iterate that element to find columns and iterate that columns to store data in the list.您需要首先识别表元素,然后迭代该元素以查找列并迭代该列以将数据存储在列表中。

Use WebDriverWait() and expected condition to avoid synchronization issue.使用WebDriverWait()和预期条件来避免同步问题。

Create two list one to add table data and other to add cell data.创建两个列表,一个添加表格数据,另一个添加单元格数据。

List<WebElement> tableElements =new WebDriverWait(driver,10).until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.tagName("table")));
        
        List<List<String>> tableData = new ArrayList<List<String>>();
        for(WebElement table : tableElements)           
        {  
            List<String> cellData = new ArrayList<String>();
            List<WebElement> lstcolums=table.findElements(By.xpath("./tbody//tr//td"));
            for (WebElement td : lstcolums)
            {
                cellData.add(td.getText());
                
            }
            tableData.add(cellData);
        }
        
        System.out.println(tableData);

Output: Output:

[[Coupon-Code 1, Unused, Coupon-Code 2, Used], [Coupon-Code 1, Used, Coupon-Code 2, Unused]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM