Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select nodes by matching text

Tags:

ruby

nokogiri

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 method in Nokogiri that would get me all p elements that contain the text "Apple"? (The example element above would match, for instance).

like image 741
Zando Avatar asked Sep 24 '09 23:09

Zando


People also ask

Can we use text () in XPath?

5) XPath Text() FunctionThe XPath text() function is a built-in function of selenium webdriver which is used to locate elements based on text of a web element. It helps to find the exact text elements and it locates the elements within the set of text nodes. The elements to be located should be in string form.

How do I select text in XPath?

Do note that /html/text() doesn't select all text nodes in the document -- only the text nodes that are children (not descendents) of the top, html element. You probably want /html//text() . Some knowledge and understanding of XPath is typically required in order to construct XPath expressions.

Which XPath function is used to extract all the elements which matches a particular text value?

We can extract all the elements that match the given text value using the XPath contains() function throughout the webpage.

Is used to select in XPath?

In XPath, path expression is used to select nodes or node-sets in an XML document. The node is selected by following a path or steps.


1 Answers

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" 
like image 146
the Tin Man Avatar answered Oct 12 '22 02:10

the Tin Man