我有一些看起来像这样的html:
<html>
<body>
<a href="www.google.com">text</a>
</body>
</html>
如何a
通过使用显示“查找包含文本内容的任何链接”的选择器来获得?我已经了解了text-pred
,但这只是返回文本,而不是带有文本的标签。
我在 Enlive 论坛上找到了这个答案。为方便起见,我将其内联:
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/