Question

If I have a bunch of elements like:

<p>A paragraph <ul><li>Item 1</li><li>Apple</li><li>Orange</li></ul></p>

Is there a built in nokogiri method that would get me all, for example, p elements that contain the text "Apple"? (the example element above would match, for instance).

Was it helpful?

Solution

Nokogiri can do this (now) using jQuery extensions to CSS:

require 'nokogiri'

html = '
<html>
  <body>
    <p>foo</p>
    <p>bar</p>
  </body>
</html>
'

doc = Nokogiri::HTML(html)
doc.at('p:contains("bar")').text.strip
=> "bar"

OTHER TIPS

Here is an XPath that works:

require 'nokogiri'

doc = Nokogiri::HTML(DATA)
p doc.xpath('//li[contains(text(), "Apple")]')

__END__
<p>A paragraph <ul><li>Item 1</li><li>Apple</li><li>Orange</li></ul></p>

Hope that helps

You can also do this very easily with Nikkou:

doc.search('p').text_includes('bar')

Try using this XPath:

p = doc.xpath('//p[//*[contains(text(), "Apple")]]')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top