【问题标题】:How to get the href attribute value using enlive如何使用enlive获取href属性值
【发布时间】:2016-01-09 03:53:53
【问题描述】:

我是 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 和 value 2。我怎样才能完成它?

【问题讨论】:

  • 感谢@jmargolisvt,更改 html/attr?到 html/attr= 不起作用。

标签: clojure enlive


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    我使用这个小函数是因为 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"
    

    【讨论】:

    • 谢谢@jmargolisvt,我在我的代码中试过这个(defn data [] (html/select (fetch-url base-url) [:span.f10 [: a (html/attr? :href)]])) (defn get-attr [node attr] #_=> (some-> node :attrs attr)) (defn get-api [] (get-attr data :href )) 并尝试执行 get-api 并返回 nil。任何想法?再次感谢您的帮助。
    • 您将“数据”定义为defn 的函数。你只需要def
    猜你喜欢
    • 2011-06-11
    • 1970-01-01
    • 2021-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-14
    • 1970-01-01
    相关资源
    最近更新 更多