Nokogiri: How to select nodes by matching text?

流过昼夜 提交于 2019-12-17 10:19:36

问题


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


回答1:


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"



回答2:


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




回答3:


You can also do this very easily with Nikkou:

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



回答4:


Try using this XPath:

p = doc.xpath('//p[//*[contains(text(), "Apple")]]')


来源:https://stackoverflow.com/questions/1474688/nokogiri-how-to-select-nodes-by-matching-text

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!