Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xpath: how do you select the second text node (specific text node)

Tags:

xpath

nokogiri

consider a html page

<html>
apple

orange

drugs

</html>

how can you select orange using xpath ?

/html/text()[2]

doesn't work.

like image 931
pingu Avatar asked Nov 28 '25 20:11

pingu


2 Answers

You cant do it directly by selecting. You need to call an xpath string function to cut the text() to get the string you want

substring-after(/html/text()," ") // something like this,

here is a list of string functions

like image 75
Andrew Keith Avatar answered Dec 01 '25 00:12

Andrew Keith


If the strings are separated with <br> it works

  doc = Nokogiri::HTML("""<html>
  apple
  <br>
  orange
  <br>
  drugs
  </html>""")
  p doc.xpath('//text()[2]') #=> orange
like image 45
akuhn Avatar answered Nov 30 '25 22:11

akuhn



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!