Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve Text Between Two Child Elements With Text

I'm wondering if there is any way to easily retrieve text that is sandwiched between two child elements with text? In this particular case, I'm looking to extract the text USD.

<div class="indemandProgress-raised ng-binding">
    <span class="indemandProgress-raisedAmount ng-binding" gogo-test="raised">
        $6,811,034
    </span>
    USD
    <span class="ng-binding">
        total funds raised
    </span>
</div>

Actual Format of Code in Browser

<div class="indemandProgress-raised ng-binding">
<span class="indemandProgress-raisedAmount ng-binding" gogo-test="raised">$6,811,034</span> USD <span class="ng-binding">total funds raised</span>
</div>

Is this possible with XPATH alone or would I have to extract all of the text and then parse it?

It has to work with Selenium.

like image 657
oldboy Avatar asked Jun 03 '26 04:06

oldboy


1 Answers

You've already accepted answer, but note that text.split()[1] is quite unreliable solution and it might not be applicable in other (in most) cases. For instance, if first text node contains spaces

$ 6,811,034

You can try this solution:

element = browser.find_element_by_class_name('indemandProgress-raisedAmount')
result = browser.execute_script('return arguments[0].childNodes[2].textContent;', element).strip()

Note that div has following 5 child nodes:

  1. Empty string (index 0)
  2. span node (index 1)
  3. Text node "USD" (index 2)
  4. Another span (index 3)
  5. Another empty string (index 4)

You need to get text content of third child node and childNodes[2].textContent allows you to do that

like image 148
Andersson Avatar answered Jun 04 '26 16:06

Andersson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!