Andrew
Andrew

Reputation: 51

Nokogiri: how to parse text fragment?

I have such example:

html= <<EOT
<div>Some text1
  <p>Some text2</p>
</div>
EOT
doc = Nokogiri::HTML(html)
puts doc.css('div').text

This makes:

Some text1
  Some text2

But i need "Some text1" only

Upvotes: 3

Views: 957

Answers (2)

mu is too short
mu is too short

Reputation: 434615

One XPath expression and a strip will get you there:

some_text1 = doc.xpath('//div/text()[1]').text.strip

Upvotes: 1

Lars Haugseth
Lars Haugseth

Reputation: 14881

doc.css('div').children.first.text
# => "Some text1\n  "

doc.css('div').children.first.text.rstrip
# => "Some text1" 

Upvotes: 2

Related Questions