简体   繁体   中英

Selenium xpath - alternative of text() to locate an element using inner text?

I am attempting to create a unique XPATH to select a checkbox using selenium in a table on a webpage.

The HTML looks like:

<tr ng-repeat="item in tests ">
   <td class="ng-binding">
       <span test: 'fa fa-cube greeniconcolor'}[item.type]"/>
       <span ng-show="item.type !='test' && item.type !='testset'">
       Test                 
      <div class="box-tools pull-right">
         <input type="checkbox" ng-model="selected_checkbox[$index]"/>
      </div>
   </td>
 </tr>

I would expect that I would be able to have an XPATH that looks like:

.//td[text()='Test']//input

to be able to click the checkbox, however that does not work. If I change it to contains and use the '.' notation instead of text() it does work:

.//td[contains(., 'Test')]//input

However if I do .='Test' it does not work. The reason I cannot use the contains() method is that the table also has Test2 in it and that is also selected.

Any advice as to how come if I have other elements inside the <tr> tag I cannot use the text() method would be appreciated!

Any advice as to how come if I have other elements inside the tag I cannot use the text() method would be appreciated!

You should try using normalize-space() function of xpath which is used to strips leading and trailing white-space from a string, replaces sequences of whitespace characters by a single space, and returns the resulting string as below :-

.//td[normalize-space(.)='Test']//input

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