簡體   English   中英

Selenium 讀取復雜表結構

[英]Selenium read complex table structure

我在我的 Java 項目中使用 Selenium。 Selenium 在測試中購買優惠券,然后想在優惠券概覽中看到它們。 如果用戶之前購買了一些優惠券包,那里可以有多個優惠券包。

頁面上的表結構如下所示:

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

我還沒有找到閱讀優惠券的方法。 我想將它們存儲在一個列表中,HTML 頁面的每個表都應該對應於列表中的一個條目,並包含優惠券代碼及其使用/未使用的值。

你知道我該如何實現它嗎?

我已經做了一些事情

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

但在這里我無法閱讀表格的條目....

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

從每個表中獲取 tr 標記,然后 td,現在您使用 getText() 獲取文本

您需要首先識別表元素,然后迭代該元素以查找列並迭代該列以將數據存儲在列表中。

使用WebDriverWait()和預期條件來避免同步問題。

創建兩個列表,一個添加表格數據,另一個添加單元格數據。

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]]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM