1

我正在尝试使用 clojure 的 enlive 库来抓取网站。对应的 CSS 选择器是:

body > table:nth-child(2) > tbody > tr > td:nth-child(3) > table > tbody > tr > td > table > tbody > tr:nth-child(n+3)

我已经使用 jquery 测试了上面的选择器,它可以工作。但我不知道如何将上面的内容翻译成 enlive 的选择器语法。我试图写一些类似的东西:

(ns vimindex.core
  (:gen-class)
  (:require [net.cgrand.enlive-html :as html]))

(def ^:dynamic *vim-org-url* "http://www.vim.org/scripts/script_search_results.php?order_by=creation_date&direction=descending")
(defn fetch-url [url]
  (html/html-resource (java.net.URL. url)))

(defn scrape-vimorg []
  (println "Scraping vimorg")
  (println
    (html/select (fetch-url *vim-org-url*)
                 [:body :> [:table (html/nth-child 2)] :> :tbody :> :tr :> [:td (html/nth-child 3)] :> :table :> :tbody :> :tr :> :td :> :table :> :tbody :> [:tr (html/nth-child 1 3)]])))
;                  body  >   table:nth-child(2)         >  tbody  >  tr  >   td:nth-child(3)         >  table  >  tbody  >  tr  >  td  >  table  >  tbody  >   tr:nth-child(n + 3)
; Above selector works with jquery

(defn -main
  [& args]
  (scrape-vimorg))

但我得到一个空洞的回应。你能告诉我如何用 enlive 的语法翻译上面的 CSS 选择器吗?

非常感谢。

编辑:包括完整的代码。

4

2 回答 2

0

您缺少的语法是使用伪选择器的元素周围的一组额外括号。所以你想要这样的东西:

 [:body :> [:table (html/nth-child 2)] :> :tbody :> :tr 
 [:td (html/nth-child 3)] :> :table :> :tbody :> :tr :> :td :> 
 :table :tbody :> [:tr (html/nth-child 1 3)]])
于 2016-01-08T23:24:40.520 回答
0

看起来浏览器(至少我的 firefox 版本)在其 DOM 表示中添加了一个 tbody 标记,即使它不在实际源中也是如此。

Enlive 不这样做。因此,当您省略 tbody 部分时,您的代码应该可以工作。

于 2017-01-09T23:03:12.177 回答