Clojure:Enlive选择器中的自定义函数?
下面是一个例子,我直接在选择器向量中使用html/文本Clojure:Enlive选择器中的自定义函数?,clojure,enlive,Clojure,Enlive,下面是一个例子,我直接在选择器向量中使用html/文本 (:use [net.cgrand.enlive-html :as html]) (defn fetch-url [url] (html/html-resource (java.net.URL. url))) (defn parse-test [] (html/select (fetch-url "https://news.ycombinator.com/") [:td.title :a html/text]))
(:use [net.cgrand.enlive-html :as html])
(defn fetch-url [url]
(html/html-resource (java.net.URL. url)))
(defn parse-test []
(html/select
(fetch-url "https://news.ycombinator.com/")
[:td.title :a html/text]))
调用parse test返回包含黑客新闻标题的数据结构:
("In emergency cases a passenger was selected and thrown out of the plane. [2004]"
"“Nobody expects privacy online”: Wrong."
"The SCUMM Diary: Stories behind one of the greatest game engines ever made" ...)
酷
是否可以使用自定义函数结束选择器向量,该函数将返回文章URL列表
类似于:[:td.title:a strhttps://news.ycombinator.com/ :href:attrs%]
编辑:
以下是实现这一目标的方法。我们可以编写自己的选择函数:
(defn select+ [coll selector+]
(map
(peek selector+)
(html/select
(fetch-url "https://news.ycombinator.com/")
(pop selector+))))
(def href
(fn [node] (:href (:attrs node))))
(defn parse-test []
(select+
(fetch-url "https://news.ycombinator.com/")
[:td.title :a href]))
(parse-test)
正如您在评论中所建议的,我认为将节点的选择和转换分开是最清楚的 Enlive本身提供选择器和转换器。查找节点的选择器,以及转换节点的转换器。如果您想要的输出是html,那么您可能会使用选择器和转换器的组合来实现您想要的结果 然而,鉴于您只是在寻找一系列地图上的数据,也许您可以跳过转换位,只需使用序列理解,如下所示:
(defn parse-test []
(for [s (html/select
(fetch-url "https://news.ycombinator.com/")
[:td.title :a])]
{:title (first (:content s))
:link (:href (:attrs s))}))
(take 2 (parse-test))
;; => ({:title " \tStartup - Bill Watterson, a cartoonist's advice ",
:link "http://www.zenpencils.com/comic/128-bill-watterson-a-cartoonists-advice"}
{:title "Drug Agents Use Vast Phone Trove Eclipsing N.S.A.’s",
:link "http://www.nytimes.com/2013/09/02/us/drug-agents-use-vast-phone-trove-eclipsing-nsas.html?hp&_r=0&pagewanted=all"})
我怀疑这是不可能做到的。我宁愿从选择器向量中删除html/文本并执行:map strhttps://news.ycombinator.com/ :href:attrs%parse test或者可能有人找到了一种方法,可以在不转义向量的情况下获得相同的结果:/