Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

With enlive, how do you get the tag of a link based off of its content?

Tags:

clojure

enlive

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.

like image 494
Daniel Kaplan Avatar asked Mar 28 '13 04:03

Daniel Kaplan


1 Answers

I found this answer on the Enlive forum. I'll inline it for convenience:

Question

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...

Answer

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/
like image 179
Daniel Kaplan Avatar answered Sep 28 '22 03:09

Daniel Kaplan