如何通过匹配文本选择节点 [英] How to select nodes by matching text

查看:45
本文介绍了如何通过匹配文本选择节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一堆元素,例如:

If I have a bunch of elements like:

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

Nokogiri 中是否有内置方法可以获取包含文本Apple"的所有 p 元素?(例如,上面的示例元素将匹配).

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

推荐答案

Nokogiri 可以(现在)使用 CSS 的 jQuery 扩展来做到这一点:

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"

这篇关于如何通过匹配文本选择节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆