【问题标题】:Strange output in Clojure Web CrawlerClojure Web Crawler 中的奇怪输出
【发布时间】:2013-01-12 14:20:11
【问题描述】:

我有以下问题。我正在为学校作业做 WebCrawler,我正在 Clojure 中做。这是代码。

(defn crawl [url current-depth max-depth]
(def hrefs (get-links url))
(if (< current-depth max-depth)
    (map crawl hrefs (iterate eval (inc current-depth)) (iterate eval max-depth))
    hrefs))

(defn get-links [page] 
($ (get! page) td "a[href]" (attr "abs:href")))

get!$ 函数不是我写的,我是从这里拿的:https://github.com/mfornos/clojure-soup/blob/master/src/jsoup/soup.clj

我的问题是,当我从 repl 调用 (crawl "http://bard.bg" 0 0) 时,我得到以下输出:

("http://www.bard.bg/genres/?id=1" "http://www.bard.bg/genres/?id=2" "http://www.bard.bg/genres/?id=4" "http://www.bard.bg/genres/?id=5" "http:/
("http://www.bard.bg/genres/?id=1" "http://www.bard.bg/genres/?id=2" "http://www.bard.bg/genres/?id=4" "http://www.bard.bg/genres/?id=5" "http:/
("http://www.bard.bg/genres/?id=1" "http://www.bard.bg/genres/?id=2" "http://www.bard.bg/genres/?id=4" "http://www.bard.bg/genres/?id=5" "http://www.bard.bg/genres/?id=6" "http://www.bard.bg/genres/?id=10" "http://www.bard.bg/genres/?id=17" "http://www.bard.bg/genres/?id=24"
...

那么第一个2lazyseqs 是从哪里来的呢?为什么他们未完成

似乎问题出在 Clojure-Soup 中,更具体地说是:

(defmacro $ [doc & forms]
   (let [exprs# (map #(if (string? %) `(select ~%)
                  (if (symbol? %) `(select ~(str %))
                     (if (keyword? %) `(select ~(str "#"(name %)))
                        %))) forms)]
 `(->> ~doc ~@exprs#)))`

【问题讨论】:

标签: html recursion web clojure output


【解决方案1】:

我无法重现您描述的问题。在我的例子中,(crawl "http://bard.bg" 0 0) 返回一个包含 174 个字符串的列表。

但是,我想借此机会指出defcrawl 函数中的错误用法。你应该使用let 而不是def。此外,不要使用(iterate eval ...),而是使用repeat

(defn crawl [url current-depth max-depth]
  (let [hrefs (get-links url)]
    (if (< current-depth max-depth)
      (map crawl hrefs (repeat (inc current-depth)) (repeat max-depth))
      hrefs)))

讨论见let vs def in clojure

【讨论】:

  • 是的,(count (crawl "bard.bg" 0 0)) 也为我返回 174,但是“crawl”的输出有这个奇怪的 (... (... ( ".." "..")
  • @user1972465,我猜是终端打印的问题。您是否尝试过更改窗口的大小?在未最大化的窗口中重试。如果它有帮助,我会感到惊讶,但它可能会起作用。
  • 这是我的第一个想法,它是某种打印问题,但我决定不是在我这样做的时候(def something (crawl ...)),并且“something”也有这个好处。谢谢您的帮助! :))
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-03
  • 2015-02-18
  • 2011-06-14
  • 2013-06-04
相关资源
最近更新 更多