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).
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.
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.
We can extract all the elements that match the given text value using the XPath contains() function throughout the webpage.
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.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With