简体   繁体   中英

Selenium read complex table structure

I am using Selenium in my Java project. Selenium buys coupons in a test and then wants to see them in the coupon overview. 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.

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

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.

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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