AaronDT AaronDT - 1 month ago 5
Ruby Question

How to get text after tag within li element

I am trying to get the text within a

<li>
element that I identify with help of
span
elements that contain "Inhalt:".

The text I want to get is "0,75l".

This is the HTML code:

<li class="product--tax is-left">
<span class="label--purchase-unit">Inhalt:</span>
0,75 l #text I want to get
</li>


If been trying this, however it doesn't seem to work:

doc.search("[text()*='Inhalt:']").parent.xpath('text()')

Answer

You're trying to find the text node that follows the <span>. That's easily done once you know where the <span> is:

require 'nokogiri'

doc = Nokogiri::HTML(<<EOT)

<li class="product--tax is-left">
   <span class="label--purchase-unit">Inhalt:</span>
0,75 l
</li>
EOT

These are various ways to get there:

doc.at('li span').next_sibling.text.strip # => "0,75 l"
doc.at('li.product--tax span.label--purchase-unit').next_sibling.text.strip # => "0,75 l"
doc.at('.label--purchase-unit').next_sibling.text.strip # => "0,75 l"
doc.at('span.label--purchase-unit').next_sibling.text.strip # => "0,75 l"
Comments