skip to Main Content

I want to read the data which is inside the second div:

<div class="my-3">
  <div class="d-flex justify-content-between">Monthly:</div>
  <div>0 / 30,000</div>
</div>

In the above markup, I want to read the div which contains the string: 0 / 30,000

I was able to navigate to the first div which contains the string "Monthly:" with this XPath:

//*[normalize-space()='Monthly:']

How can I select the second div below after that?

2

Answers


  1. Use this:

    //*[normalize-space()='Monthly:']/following-sibling::div
    
    Login or Signup to reply.
  2. Limitations of currently accepted answer

    The XPath in the currently accepted answer,

    //*[normalize-space()='Monthly:']/following-sibling::div
    

    works for OP’s exact case where there is a single div following the targeted label,

    <div class="my-3">
      <div class="d-flex justify-content-between">Monthly:</div>
      <div>0 / 30,000</div>
    </div>
    

    but can produce different results if there are multiple div sibling elements following the target.

    For example, consider this markup:

    <div class="my-3">
      <div class="d-flex justify-content-between">Monthly:</div>
      <div>0 / 30,000</div>
      <div>more</div>
      <div>and more</div>
    </div>
    

    In this case, it won’t just be <div>0 / 30,000</div> that’s selected, but

      <div>0 / 30,000</div>
      <div>more</div>
      <div>and more</div>
    

    More robust XPath for labeled data

    To select only the immediately following div element, use this XPath instead:

    //*[normalize-space()='Monthly:']/following-sibling::*[1][self::div]
    

    To select only the immediately following element of any name:

    //*[normalize-space()='Monthly:']/following-sibling::*[1]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search