1

I have a button like below. I am not sure how to grab it by it's text which is Search. There are many buttons on this page.

<button _ngcontent-dqg-c23="" class="cp-mat-small-btn mat-flat-button mat-accent" color="accent" mat-flat-button="" ng-reflect-disabled="false" ng-reflect-color="accent"><span class="mat-button-wrapper">
    Search
  </span><div class="mat-button-ripple mat-ripple" matripple="" ng-reflect-centered="false" ng-reflect-disabled="false" ng-reflect-trigger="[object HTMLButtonElement]"></div><div class="mat-button-focus-overlay"></div></button>

I tried :

WebElement searchBtn = webDriver.find_element_by_xpath('//button[text()="Search"]');

But getting error:

    | > Task :compileTestJava
gauge_1          | /tipu/src/test/java/CalmImplementation.java:16: error: unclosed character literal
gauge_1          |         WebElement searchBtn = webDriver.find_element_by_xpath('//button[normalize-space()="Search"]');
gauge_1          |                                                                ^
gauge_1          | /tipu/src/test/java/CalmImplementation.java.java:16: error: unclosed character literal
gauge_1          |         WebElement searchBtn = webDriver.find_element_by_xpath('//button[normalize-space()="Search"]');
gauge_1          |                                                                                                     ^
gauge_1          | /tipu/src/test/java/CalmImplementation.java.java:16: error: not a statement
gauge_1          |         WebElement searchBtn = webDriver.find_element_by_xpath('//button[normalize-space()="Search"]');
gauge_1          |                                                                         ^
gauge_1          | 3 errors
gauge_1          | 
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
VictorGram
  • 2,521
  • 7
  • 48
  • 82

2 Answers2

1

You can use XPATH:

//button[normalize-space()="Search"]

Note that search by text()="Search" won't work as button text is not exactly "Search" - text content contains linesbreaks/spaces

DonnyFlaw
  • 581
  • 3
  • 9
1

find_element_by_xpath() isn't a valid method when using Selenium's Java client.

Again, the WebElement with text as Search is within the child <span> of it's parent <button> and an Angular element.

So to identify the element by it's text i.e. Search you you need to induce WebDriverWait for the elementToBeClickable() and you can use either of the following Locator Strategies:

  • Using xpath and contains():

    WebElement searchBtn = new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//button/span[contains(., 'Search')]")));
    
  • Using xpath and normalize-space():

    WebElement searchBtn = new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//button/span[normalize-space()='Search']")));
    
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352