如何在enlive中选择特定类型的第n个元素?

时间:2010-04-23 01:53:41

标签: clojure

我正在尝试使用基于表格的布局从页面中抓取一些数据。因此,为了获得一些数据,我需要在第一个表内第五个表内的第二个表内获得第三个表。我试图使用enlive,但无法弄清楚如何使用nth-of-type和其他选择器步骤。更糟糕的是,有问题的页面在正文中有一个顶级表,但是(select data [:body:>:table])由于某种原因返回6个结果。我到底做错了什么?

1 个答案:

答案 0 :(得分:7)

对于nth-of-type,以下示例是否有帮助?

user> (require '[net.cgrand.enlive-html :as html])
user> (def test-html
           "<html><head></head><body><p>first</p><p>second</p><p>third</p></body></html>")
#'user/test-html
user> (html/select (html/html-resource (java.io.StringReader. test-html))
                   [[:p (html/nth-of-type 2)]])
({:tag :p, :attrs nil, :content ["second"]})

不知道第二个问题。你的方法似乎适用于天真的测试:

user> (def test-html "<html><head></head><body><div><p>in div</p></div><p>not in div</p></body></html>")
#'user/test-html
user> (html/select (html/html-resource (java.io.StringReader. test-html)) [:body :> :p])
({:tag :p, :attrs nil, :content ["not in div"]})

有机会查看您的实际HTML吗?

更新: (回应评论)

这是另一个例子,其中“返回的<p>里面的第二个<div>内的任何一个<div>”:

user> (def test-html "<html><head></head><body><div><p>this is not the one</p><p>nor this</p><div><p>or for that matter this</p><p>skip this one too</p></div></div><span><p>definitely not this one</p></span><div><p>not this one</p><p>not this one either</p><div><p>not this one, but almost</p><p>this one</p></div></div><p>certainly not this one</p></body></html>")
#'user/test-html
user> (html/select (html/html-resource (java.io.StringReader. test-html))
                   [[:div (html/nth-of-type 2)] :> :div :> [:p (html/nth-of-type 2)]])
({:tag :p, :attrs nil, :content ["this one"]})
相关问题