如何使用enlive获取href属性值

时间:2016-01-08 18:26:30

标签: clojure enlive

我是Clojure的新手并且很活跃。

我有像这样的HTML

<SPAN CLASS="f10"><A HREF="value1" title="...." TARGET="detail">....</A></SPAN></DIV><DIV CLASS="p5"><SPAN CLASS="f10"><A HREF="value2" title="..." TARGET="detail">.....</A></SPAN>

我试过这个

(html / select(fetch-url base-url )[:span.f10 [:a(html / attr?:href)]]))

但它会返回此

({:tag :a,
  :attrs
  {:target "detail",
   :title
   "...",
   :href
   "value1"},
  :content ("....")}
 {:tag :a,
  :attrs
  {:target "detail",
   :title
   "....",
   :href
   "value2"},
  :content
  ("....")}

我想要的只是输出中的value1和value2。我怎么能完成它?

2 个答案:

答案 0 :(得分:1)

select返回匹配的节点,但您仍需要提取其href属性。为此,您可以使用attr-values

(mapcat #(html/attr-values % :href)
      (html/select (html/html-resource "sample.html") [:span.f10 (html/attr? :href)]))

答案 1 :(得分:0)

我使用这个小函数,因为Enlive attr函数不返回值。你基本上只是走散列来获得价值。

user=> (def data {:tag :a, :attrs {:target "detail", :title "...", :href "value1"}})
#'user/data

user=> (defn- get-attr [node attr]
       #_=>   (some-> node :attrs attr))
#'user/get-attr

user=> (get-attr data :href)
"value1"