PageRenderTime 46ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/src/vision/craig.clj

http://github.com/alvinlai/vision
Clojure | 77 lines | 55 code | 13 blank | 9 comment | 1 complexity | 3e0841670a54d96d580ad54d8ec90b9a MD5 | raw file
  1. (ns vision.craig
  2. (:import java.net.URL)
  3. (:require [clojure.contrib.string :as str-utils :only (substring? lower-case)])
  4. (:use hiccup.core
  5. vision.views
  6. vision.helpers))
  7. (use 'net.cgrand.enlive-html)
  8. ; filter function posts only with pics
  9. (defn got-pic?
  10. [l]
  11. (= "p" (:class (:attrs (first (drop 7 (:content l)))))))
  12. (defn search-url
  13. [query-str]
  14. (str "http://sfbay.craigslist.org/search/cto?query=" query-str "&srchType=T&minAsk=&maxAsk="))
  15. ; transform into nice hashes
  16. (defn process-post
  17. [post]
  18. (let [p (first (drop 3 (:content post)))]
  19. {:title (first (:content p))
  20. :link (:href (:attrs p))
  21. :price (.trim (first (drop 4 (:content post))))}))
  22. (defn get-raw-posts
  23. [query-str]
  24. (-> (search-url query-str) java.net.URL. html-resource
  25. (select [:.row])))
  26. (defn get-posts-with-pics
  27. [query-str]
  28. (let [links (get-raw-posts query-str)]
  29. (map process-post
  30. (filter got-pic? links))))
  31. (defn html-format-post
  32. [post]
  33. (html
  34. [:li
  35. [:a {:href (:link post) :target "_blank"} (:title post)]
  36. (:price post)]))
  37. (defn html-craig-query
  38. [query-str]
  39. (let [rand-query-str (str "/craig/" (rand-nth ["mustang" "bmw" "mercedes" "honda" "volkswagen"]))]
  40. (layout
  41. (html
  42. [:h2 (str "Simple Craiglist Parser for " query-str) ]
  43. [:p "Protip: Try changing the url to "
  44. (link-to rand-query-str rand-query-str)
  45. " instead."]
  46. (map html-format-post (get-posts-with-pics query-str))))))
  47. ;;;;; for repl debugging
  48. ; redundant, after search query is called in url directly
  49. (defn title-filter
  50. [title]
  51. #(str-utils/substring? title (str-utils/lower-case (:title %))))
  52. (defn print-post
  53. [post]
  54. (let [p post]
  55. (println (str "- " (:title p) " :: " (:link p)))))
  56. (defn pres
  57. [filter-str]
  58. (map print-post (get-posts-with-pics filter-str))
  59. ;(map print-post (filter (title-filter filter-str)
  60. ;(get-posts-with-pics)))
  61. )
  62. ; (map print-post carpics)
  63. ; (print-post (first carpics))
  64. ; (count carpics)