Home > Back-end >  Locate a row with a specific text and click that row's icon in the last column
Locate a row with a specific text and click that row's icon in the last column

Time:02-21

I want to find specific row in a mat-table, and I want to click a specific mat-icon. However I don't know how to use xpath in the case of mat-icon. My code is find the table, and iterate over the rows to find specific row. After that it should click on mat-icon in the last column. Maybe can I find it by its name? Here is my code:

public void clickIconFromSelectedRow(String text, String icon) {
    WebElement baseTable = driver.findElement(By.xpath("//mat-table[@role='table']"));
    List<WebElement> tableRows = baseTable.findElements(By.xpath("//mat-row[@role='row']"));
    for (WebElement row : tableRows){
        List<WebElement> cols = row.findElements(By.xpath("//mat-cell[@role='cell']"));
        for (WebElement col : cols) {
            if (col.getText().equals(text)) {
                driver.findElement(By.xpath("SOME XPATH AND   text   TEXT")).click();
            }
        }
    }
}

Here is the HTML for your information

Note: in the last column, there must be several mat-icons.

CodePudding user response:

You need to consider a couple of things here:

  • You are constructing the list tableRows with respect to the WebElement baseTable. So within the xpath instead of By.xpath("//mat-row[@role='row']") you need By.xpath("./mat-row[@role='row']")

  • The text Test is actually within the descendent of the element //mat-cell[@role='cell'] so you may like to go deeper as ./mat-cell[@role='cell']/div/div[text()].

  • Your effective code block will be:

    public void clickIconFromSelectedRow(String text, String icon) {
        WebElement baseTable = driver.findElement(By.xpath("//mat-table[@role='table']"));
        List<WebElement> tableRows = baseTable.findElements(By.xpath("./mat-row[@role='row']"));
        for (WebElement row : tableRows){
            List<WebElement> cols = row.findElements(By.xpath("./mat-cell[@role='cell']/div/div[text()]"));
            for (WebElement col : cols) {
                if (col.getText().equals(text)) {
                    driver.findElement(By.xpath("SOME XPATH AND   text   TEXT")).click();
                }
            }
        }
    }
    

CodePudding user response:

Really, I think you are over-complex a simple problem using xPath. I I imagine you has a mat-table with a column like

<ng-container matColumnDef="position">
    <th mat-header-cell *matHeaderCellDef> Actions</th>
    <td mat-cell *matCellDef="let element;let i=dataIndex"> 
      <button mat-icon-button (click)="doSomething(element,i)">
        <mat-icon>more_vert</mat-icon>
      </button>
    </td>
</ng-container>

Why not search the row asking the dataSource and use?

   this.doSomething(element,i)
  • Related