Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I select an element with its text content via CSS not XPath?

Tags:

ruby

nokogiri

"Nokogiri: How to select nodes by matching text?" can do this via XPath, however, I am looking for a way to use a CSS select that matches the text of element.

PyQuery and PHPQuery can do this. Isn't there a jQuery API lib for Ruby?

like image 438
h34y Avatar asked Sep 28 '09 01:09

h34y


1 Answers

Nokogiri (now) implements jQuery selectors, making it possible to search the text of a node:

For instance:

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"
like image 182
the Tin Man Avatar answered Oct 29 '22 14:10

the Tin Man