Nokogiri: How to select nodes by matching text?

2019-01-10 12:16发布

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).

标签: ruby nokogiri
4条回答
贼婆χ
2楼-- · 2019-01-10 13:00

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"
查看更多
\"骚年 ilove
3楼-- · 2019-01-10 13:04

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

查看更多
我命由我不由天
4楼-- · 2019-01-10 13:07

You can also do this very easily with Nikkou:

doc.search('p').text_includes('bar')
查看更多
走好不送
5楼-- · 2019-01-10 13:21

Try using this XPath:

p = doc.xpath('//p[//*[contains(text(), "Apple")]]')
查看更多
登录 后发表回答