-
Notifications
You must be signed in to change notification settings - Fork 11
/
reaver.clj
344 lines (277 loc) · 7.03 KB
/
reaver.clj
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
(ns reaver
(:require [clojure.string :as string])
(:import [org.jsoup Jsoup]
[org.jsoup.parser Parser Tag]
[org.jsoup.nodes Attribute Attributes Comment DataNode
Document DocumentType Element Node
TextNode]
[org.jsoup.select Elements]))
;;
;; Parse HTML
;;
(defn parse
"Parses a string representing a full HTML document
into Jsoup."
[^String html]
(when html
(Jsoup/parse html)))
(defn parse-fragment
"Parses a string representing a fragment of HTML
into Jsoup."
[^String html]
(when html
(.. (Jsoup/parseBodyFragment html) (body) (childNode 0))))
;;
;; Translate Jsoup to EDN
;;
(defn ^:private to-keyword
"Converts a string into a lowercase keyword."
[s]
(-> s string/lower-case keyword))
(defn reduce-into
"Imperfectly mimics 'into' with 'reduce' and 'conj'
for better performance."
[empty-coll xs]
(reduce conj empty-coll xs))
(defprotocol EDNable
(to-edn [jsoup]
"Converts Jsoup into an edn representation of HTML.
{:type Keyword
:tag Keyword|nil
:attrs {Keyword String, ...}|nil
:content Vector|Map|String|nil}"))
(extend-protocol EDNable
Attribute
(to-edn [attr] [(to-keyword (.getKey attr))
(.getValue attr)])
Attributes
(to-edn [attrs] (not-empty (reduce-into {} (map to-edn attrs))))
Comment
(to-edn [comment] {:type :comment
:content [(.getData comment)]})
DataNode
(to-edn [node] (str node))
Document
(to-edn [doc] {:type :document
:content (not-empty
(reduce-into [] (map to-edn (.childNodes doc))))})
DocumentType
(to-edn [doctype] {:type :document-type
:attrs (to-edn (.attributes doctype))})
Element
(to-edn [element] {:type :element
:attrs (to-edn (.attributes element))
:tag (to-keyword (.tagName element))
:content (not-empty
(reduce-into [] (map to-edn (.childNodes element))))})
Elements
(to-edn [elements] (when (> (.size elements) 0)
(map to-edn elements)))
TextNode
(to-edn [node] (.getWholeText node)))
;;
;; Select Elements
;;
(defn select
"Given HTML parsed to Jsoup and a string representing
a CSS-esque selector, select* returns Jsoup representing
any successfully selected data.
For more on selector syntax, see:
http://jsoup.org/cookbook/extracting-data/selector-syntax"
[^Node node ^String css-selector]
(let [^Elements result (.select node css-selector)]
(if (.isEmpty result)
nil
result)))
;;
;; Extract Data
;;
(defprotocol Extractable
(jsoup [x]
"Returns data in Jsoup types.")
(edn [x]
"Returns data in edn format.")
(tag [x]
"Returns a keyword representing the node's html tag (if it has one)")
(attr* [x a]
"Returns a string representing the node's value for the
supplied attribute (or nil, if it has no value)")
(attrs [x]
"Returns a map of keyword/string pairs representing the node's
attributes.")
(text [x]
"Returns a string representing all the text contained by the node.")
(data [x]
"Returns a string representing all the data (ie. from scripts)
contained by the node."))
(extend-protocol Extractable
nil
(jsoup
[_]
nil)
(edn
[_]
nil)
(tag
[_]
nil)
(attr*
[_ _]
nil)
(attrs
[_]
nil)
(text
[_]
nil)
(data
[_]
nil))
(extend-protocol Extractable
Element
(jsoup
[element]
element)
(edn
[element]
(to-edn element))
(tag
[element]
(-> (to-edn element)
:tag))
(attr*
[element attribute]
(-> (to-edn element)
(get-in [:attrs (keyword attribute)])))
(attrs
[element]
(-> (to-edn element)
:attrs))
(text
[element]
(.text element))
(data
[element]
(.data element)))
(defn one?
[^Elements elements]
(= 1 (.size elements)))
(extend-protocol Extractable
Elements
(jsoup
[elements]
(if (one? elements)
(first elements)
elements))
(edn
[elements]
(if (one? elements)
(edn (first elements))
(map edn elements)))
(tag
[elements]
(if (one? elements)
(tag (first elements))
(map tag elements)))
(attr*
[elements attribute]
(if (one? elements)
(attr* (first elements) attribute)
(map #(attr* % attribute) elements)))
(attrs
[elements]
(if (one? elements)
(attrs (first elements))
(map attrs elements)))
(text
[elements]
(if (one? elements)
(text (first elements))
(map text elements)))
(data
[elements]
(if (one? elements)
(data (first elements))
(map data elements))))
(extend-protocol Extractable
TextNode
(jsoup
[node]
node)
(edn
[node]
(to-edn node))
(tag
[node]
nil)
(attr*
[node attribute]
nil)
(attrs
[node]
nil)
(text
[node]
(.getWholeText node))
(data
[node]
nil))
(defn attr
"Convenience function allowing:
(chain (attr :href) ..)
instead of requiring:
(chain #(attr* % :href) ..)"
([attribute] (fn [x] (attr* x attribute)))
([x attribute] (attr* x attribute)))
(defn chain
"Executes the supplied functions in left to right order
on an element.
(chain text parse-date)"
[& fns]
(fn [x]
((apply comp (reverse fns)) x)))
;;
;; Format Data Extractions
;;
(defn run-extraction
[source sel extraction]
(let [[selector extract] extraction
selected (sel source selector)]
(extract selected)))
(defn run-extractions
[source extractions]
(let [sel (memoize select)]
(case (count extractions)
0 (to-edn source)
1 (run-extraction source sel (first extractions))
(map (partial run-extraction source sel) extractions))))
(defn extract
"ks is a vector of keys that will be zipped into a map
with the extracted data, ie:
{(first ks) (first (run-extractions source extractions))}
If ks is nil or empty, a sequence of extracted data will
be returned instead.
Extractions are a selector (see `select`) followed by an
extractor (see `Extractable`).
(extract (parse subreddit)
[:headlines]
\".sitetable .thing .title a.title\" text)"
[source ks & extractions]
(let [extractions (partition 2 extractions)
extracted (run-extractions source extractions)]
(if (empty? ks)
extracted
(case (count extractions)
0 {(first ks) extracted}
1 {(first ks) extracted}
(zipmap ks extracted)))))
(defn extract-from
"Behaves like extract, but prior to running extractions
uses the provided selector to narrow down the data to
be searched.
This is useful, for instance, when one wants to select
a sequence of items, then extract identical information
from each."
[source selector ks & extractions]
(let [sources (select source selector)]
(map #(apply (partial extract % ks) extractions) sources)))