I've got some html that looks like this:
<html>
<body>
<a href="www.google.com">text</a>
</body>
</html>
How do I get the a
by using a selector that says "find any link with a content of text"? I've learned about text-pred
, but that just returns the text, not the tag with the text.
I found this answer on the Enlive forum. I'll inline it for convenience:
I'm trying to extract the :href attribute from a link which has the
anchor text "Next". So far I have the following selector worked up.
(html/select tree [:div#nav :span.b :a])
<div id="nav">
<span class="b"><a href="...">Back</a></span>
<span><a href="...">1</a></span>
<span><a href="...">2</a></span>
<span><a href="...">3</a></span>
<span class="b"><a href="...">Next</a></span>
</div>
The problem is that this gives several results (both "Back" and
"Next"). How can I filter this by the text above so I just get the
element I want? I'd prefer to keep the logic in the css selector
instead of looping through the results if possible...
You have different options:
[:div#nav :span.b [:a (html/has [(html/re-pred #"Next")])]]
[:div#nav :span.b [:a (html/has [(html/text-pred #(= % "Next"))])]]
but the simplest is:
[:div#nav :span.b [:a (html/pred #(= (html/text %) "Next"))]]
and you can make it clearre by rolling your own predicate:
(defn text= [s] (html/pred #(= s (html/text %))))
[:div#nav :span.b [:a (text= "Next")]]
#'text works like innerText in browsers so this selector would match <a href='#'><b>Ne<!-- boo -->xt</b></a> too/
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