0

I have an html file with some paragraphs as below:

<p> paragraph 1 </p>
<p> paragraph 2 </p>
<p> paragraph 3 </p>
<p> paragraph 4 </p>

Now I want to get the first two or three of the above paragraphs.

The snippet below only returns one paragraph based on the index I define..

doc = Nokogiri::HTML(open('test.html'))
p doc.xpath('//p[1][contains(text(), "paragraph")]')

but I want a range of paragraphs like 1..2 how can I achieve this? Thanks

tokhi
  • 19,860
  • 23
  • 91
  • 104

1 Answers1

1

Use the code as below

doc = Nokogiri::HTML(open('test.html'))
puts doc.xpath("//p[position() >= 1 and position() <= 3][contains(.,'paragraph')]")

output

paragraph 1 
paragraph 2 
paragraph 3 

Read this position()

The position function returns a number equal to the context position from the expression evaluation context.

and EqualityExpr.

Arup Rakshit
  • 113,563
  • 27
  • 250
  • 306
  • @tokhi It is a short form.. Read this [answer](http://stackoverflow.com/questions/3655549/xpath-containstext-some-string-doesnt-work-when-used-with-node-with-more) – Arup Rakshit Jun 13 '14 at 12:34