selenium-webdriverxpath

I'm looking for a better way to write this XPath without index


I'm trying to write an XPath for the HTML below.

<div class="oxd-table-card" data-v-f2168256="">
  <div class="oxd-table-row oxd-table-row--with-border" role="row" data-v-0d5ef602="" data-v-f2168256="">
    <div class="oxd-table-cell oxd-padding-cell" role="cell" style="flex: 1 1 40%;">
      <div data-v-6c07a142="">aaaaa Collings</div>
    </div>
    <div class="oxd-table-cell oxd-padding-cell" role="cell" style="flex: 1 1 40%;">
      <div data-v-6c07a142="">2023-10-02 - 2023-10-08</div>
    </div>
    <div class="oxd-table-cell oxd-padding-cell" role="cell" style="flex: 1 1 20%;">
      <div class="oxd-table-cell-actions" data-v-c423d1fa="">
        <button type="button" class="oxd-button oxd-button--medium oxd-button--text oxd-table-cell-action-space" data-v-10d463b7="" data-v-c423d1fa="">
          <!----> View
          <!---->
        </button>
      </div>
    </div>
  </div>
</div>

What I want to achieve:

  1. The XPath starts from getting the text from

    <div data-v-6c07a142>aaaaa Collings</div>
    
  2. Then moving to parent tag

    <div class="oxd-table-cell oxd-padding-cell" role="cell" style="flex: 1 1 40%;">
    
  3. Then moving to the following sibling and getting the text value from

    <div data-v-6c07a142>2023-10-02 - 2023-10-08</div>
    

The Website : https://opensource-demo.orangehrmlive.com/web/index.php/auth/login After logging in, its the 'Time' section from the left hand menu. I'm trying to get the XPath for the table in the Time module.

So far I have been able to get the text using the XPath (//div[text()='aaaaa Collings']/parent::div/following-sibling::div)[1]

I was wondering if its possible to get the text without using index in XPath.


Solution

  • I think your XPath is fine. It's probably about as good as it gets. The index isn't required in this case because it's the first element returned. You can just use,

    //div[text()='aaaaa  Collings']/parent::div/following-sibling::div
    

    with FindElement (singular) and it will pull the first (desired) element.