Warm tip: This article is reproduced from serverfault.com, please click

Selenium/java is returning empty text

发布于 2020-11-30 16:33:09

I have a table and below is the description of the html-row that I am writing selenium test for:

<mat-row _ngcontent-kgo-c23="" class="mat-row ng-star-inserted" role="row">
    <!---->
        <mat-cell _ngcontent-kgo-c23="" class="mat-cell cdk-column-id mat-column-id ng-star-inserted" role="gridcell">
            <a _ngcontent-kgo-c23="" ng-reflect-router-link="/dir,208" href="/claim/208">208</a>
        </mat-cell>
        <mat-cell _ngcontent-kgo-c23="" class="mat-cell cdk-column-firstName mat-column-firstName ng-star-inserted" role="gridcell">
        George
        </mat-cell>
</mat-row>

Here is the test :

List<WebElement> idRows = super.wait(WAIT, INTERVAL).until(driver -> driver.findElements(By.className("mat-column-id")));
webDriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
//Validate only one row exist in the search result
assertEquals(1,idRows.size());

//The result has is "208" and name "George"
WebElement firstNameInSearchResult = webDriver.findElement(By.className("cdk-column-firstName"));
System.out.println("===========>" + firstNameInSearchResult.gettext()+", " + idRows.get(0));
assertTrue(firstNameInSearchResult.getText().contains("George"));
assertTrue(idRows.get(0).getText().contains(searchId));

The System.out.println is showing empty text. And assertion following that print statement is failing. Am I doing the text validation in right way?

Questioner
Patty
Viewed
0
DebanjanB 2020-12-01 05:18:46

The elements are Angular element. So to extract the text 208 and George you have to induce WebDriverWait for the visibilityOfElementLocated() and you can use either of the following Locator Strategies:

  • Print the text 208:
    • Using xpath and getAttribute("innerHTML"):

      System.out.println(new WebDriverWait(webDriver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//mat-cell[@class='mat-cell cdk-column-id mat-column-id ng-star-inserted']/a[contains(@ng-reflect-router-link, 'dir') and contains(@href, 'claim')]"))).getAttribute("innerHTML"));
      
  • Print the text George:
    • Using xpath and getText():

      System.out.println(new WebDriverWait(webDriver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//mat-cell[@class='mat-cell cdk-column-firstName mat-column-firstName ng-star-inserted']"))).getText());