【问题标题】:How to write the following clojure enlive selector?如何编写以下 clojure enlive 选择器?
【发布时间】:2017-01-10 07:03:12
【问题描述】:

我正在尝试使用 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))

但我得到一个空洞的回应。能否请您告诉我如何将上面的 CSS 选择器翻译成 enlive 的语法。

非常感谢。

已编辑:包含完整代码。

【问题讨论】:

    标签: clojure enlive


    【解决方案1】:

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

     [: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)]])
    

    【讨论】:

    • 非常感谢您的快速响应。我按照您的建议进行了更改,但仍然无效。我仍然得到一个空洞的回应。我已经编辑了我的问题以包含完整的代码。
    • 这里有很多迷路的方法。我建议首先使用更简单的选择。三重嵌套表是学习 Enlive 的一种粗略方式。一次扩展一个选择器是找到中断位置的好方法。此外,您提供的代码不是很有用。发布 Enlive 节点怎么样?
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-08
      • 1970-01-01
      • 2014-02-25
      • 2011-05-13
      • 1970-01-01
      相关资源
      最近更新 更多