wintermeyer
wintermeyer

Reputation: 8318

Search for an element with a specific content?

Assuming I have the following HTML code:

...
<p>bla bla</p>
<h3>Foobar</h3>
<p>bla bla</p>
<p>bla bla</p>
<h3>Example</h3>
...

Is there a way to fetch the first h3 element which contains the text Foobar?

Upvotes: 0

Views: 59

Answers (2)

Mark Thomas
Mark Thomas

Reputation: 37517

Since this is HTML, I would recommend CSS selectors:

puts doc.at_css('h3:contains("Foobar")')

#=> <h3>Foobar</h3>

CSS selectors tend to make for more readable expressions when parsing HTML. I tend to use XPath only for XML or when I need the full power of XPath expressions.

Upvotes: 2

matt
matt

Reputation: 79733

You can use the contains() XPath function:

doc.xpath("//h3[contains(text(), 'Foobar')]")

Or if the target text could be in a descendent text node of h3, use:

doc.xpath("//h3[contains(.//text(), 'Foobar')]")

To fetch the first matching element directly rather than an array, use at_xpath rather than xpath.

Upvotes: 1

Related Questions