forked from numerodix/spiderfetch
/
spiderfetch.py
executable file
·254 lines (220 loc) · 8.63 KB
/
spiderfetch.py
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
#!/usr/bin/env python
#
# <desc> Web spider and fetcher </desc>
import os
import re
import sys
import tempfile
import traceback
from lib import ansicolor
import fetch
import filetype
import io
import recipe
import shutil
import spider
import time
import urlrewrite
import web
SAVE_INTERVAL = 60*30
LAST_SAVE = time.time()
def save_session(wb, queue=None):
hostname = urlrewrite.get_hostname(wb.root.url)
filename = urlrewrite.hostname_to_filename(hostname)
io.write_err("Saving session to %s ..." %
ansicolor.yellow(filename+".{web,session}"))
io.serialize(wb, filename + ".web", dir=io.LOGDIR)
if queue:
io.serialize(queue, filename + ".session", dir=io.LOGDIR)
# only web being saved, ie. spidering complete, remove old session
elif io.file_exists(filename + ".session", dir=io.LOGDIR):
io.delete(filename + ".session", dir=io.LOGDIR)
io.write_err(ansicolor.green("done\n"))
def maybesave(wb, queue):
global SAVE_INTERVAL
global LAST_SAVE
t = time.time()
if LAST_SAVE + SAVE_INTERVAL < t:
save_session(wb, queue=queue)
LAST_SAVE = t
def restore_session(url):
hostname = urlrewrite.get_hostname(url)
filename = urlrewrite.hostname_to_filename(hostname)
q, wb = None, None
if (io.file_exists(filename + ".web", dir=io.LOGDIR)):
io.write_err("Restoring web from %s ..." %
ansicolor.yellow(filename+".web"))
wb = io.deserialize(filename + ".web", dir=io.LOGDIR)
io.write_err(ansicolor.green("done\n"))
if (io.file_exists(filename + ".session", dir=io.LOGDIR)):
io.write_err("Restoring session from %s ..." %
ansicolor.yellow(filename+".session"))
q = io.deserialize(filename + ".session", dir=io.LOGDIR)
q = recipe.overrule_records(q)
io.write_err(ansicolor.green("done\n"))
return q, wb
def log_exc(exc, url, wb):
exc_filename = io.safe_filename("exc", dir=io.LOGDIR)
io.serialize(exc, exc_filename, dir=io.LOGDIR)
s = traceback.format_exc()
s += "\nBad url: |%s|\n" % url
node = wb.get(url)
for u in node.incoming.keys():
s += "Ref : |%s|\n" % u
s += "Exception object serialized to file: %s\n\n" % exc_filename
io.savelog(s, "error_log", "a")
def get_url(fetcher, wb, host_filter=False):
"""http 30x redirects produce a recursion with new urls that may or may not
have been seen before"""
while True:
try:
fetcher.launch_w_tries()
break
except fetch.ChangedUrlWarning, e:
url = urlrewrite.rewrite_urls(fetcher.url, [e.new_url]).next()
if url in wb:
raise fetch.DuplicateUrlWarning
if not recipe.apply_hostfilter(host_filter, url):
raise fetch.UrlRedirectsOffHost
wb.add_ref(fetcher.url, url)
fetcher.url = url
return fetcher.url
def qualify_urls(ref_url, urls, rule, newqueue, wb):
for url in urls:
_dump, _fetch, _spider = False, False, False
# apply patterns to determine how to qualify url
if recipe.apply_mask(rule.get("dump"), url):
_dump = True
if recipe.apply_mask(rule.get("fetch"), url):
_fetch = True
if (recipe.apply_mask(rule.get("spider"), url) and
recipe.apply_hostfilter(rule.get("host_filter"), url)):
_spider = True
# build a record based on qualification
record = {"url" : url}
if url not in wb:
if _dump:
io.write_out("%s\n" % url)
if _fetch and _spider:
record["mode"] = fetch.Fetcher.SPIDER_FETCH
elif _fetch:
record["mode"] = fetch.Fetcher.FETCH
elif _spider:
record["mode"] = fetch.Fetcher.SPIDER
if _fetch or _spider:
newqueue.append(record)
# add url to web if it was matched by anything
if _dump or _fetch or _spider:
wb.add_url(ref_url, [url])
return newqueue, wb
def process_records(queue, rule, wb):
newqueue = []
for record in queue:
maybesave(wb, queue)
url = record.get("url")
try:
(fp, filename) = io.get_tempfile()
f = fetch.Fetcher(mode=record.get("mode"), url=url, filename=filename)
url = get_url(f, wb, host_filter=rule.get("host_filter"))
filename = f.filename
# consider retrying the fetch if it failed
if f.error and fetch.err.is_temporal(f.error):
if not record.get("retry"):
record["retry"] = True
queue.append(record)
if record.get("mode") == fetch.Fetcher.SPIDER:
data = open(filename, 'r').read()
urls = spider.unbox_it_to_ss(spider.findall(data, url))
urls = urlrewrite.rewrite_urls(url, urls)
(newqueue, wb) = qualify_urls(url, urls, rule, newqueue, wb)
if record.get("mode") == fetch.Fetcher.FETCH:
shutil.move(filename,
io.safe_filename(urlrewrite.url_to_filename(url)))
except (fetch.DuplicateUrlWarning, fetch.UrlRedirectsOffHost):
pass
except KeyboardInterrupt:
q = queue[queue.index(record):]
q.extend(newqueue)
save_session(wb, queue=q)
sys.exit(1)
except Exception, exc:
log_exc(exc, url, wb)
finally:
try:
if filename and os.path.exists(filename):
os.unlink(filename)
if fp: os.close(fp)
except (NameError, OSError):
pass
pause = os.environ.get('PAUSE')
if pause:
time.sleep(int(pause))
return newqueue
def split_queue(queue, lastrule=False):
fetch_queue, spider_queue = [], []
for record in queue:
mode = record.get("mode")
if mode == fetch.Fetcher.FETCH or mode == fetch.Fetcher.SPIDER_FETCH:
r = record.copy()
r["mode"] = fetch.Fetcher.FETCH
fetch_queue.append(r)
# if this isn't the last rule, defer remaining spidering to the
# next rule
if not lastrule:
if mode == fetch.Fetcher.SPIDER or mode == fetch.Fetcher.SPIDER_FETCH:
r = record.copy()
r["mode"] = fetch.Fetcher.SPIDER
spider_queue.append(r)
return fetch_queue, spider_queue
def main(queue, rules, wb):
outer_queue = queue
for rule in rules:
depth = rule.get("depth", 1)
# queue will be exhausted in inner loop, but once depth is reached
# the contents to spider will fall through to outer_queue
outer_queue, queue = [], outer_queue
while queue:
if depth > 0:
depth -= 1
elif depth == 0:
# There may still be records in the queue, but since depth is reached
# no more spidering is allowed, so we allow one more iteration, but
# only for fetching
queue, outer_queue = split_queue(queue, rules.index(rule) == len(rules)-1)
queue = process_records(queue, rule, wb)
save_session(wb)
if __name__ == "__main__":
(parser, a) = io.init_opts("<url> ['<pattern>'] [options]")
a("--recipe", metavar="<recipe>", dest="recipe", help="Use a spidering recipe")
a("--fetch", action="store_true", help="Fetch urls, don't dump")
a("--dump", action="store_true", help="Dump urls, don't fetch")
a("--host", action="store_true", help="Only spider this host")
a("--pause", type="int", metavar="<pause>", dest="pause", help="Pause for x seconds between requests")
a("--depth", type="int", metavar="<depth>", dest="depth", help="Spider to this depth")
(opts, args) = io.parse_args(parser)
try:
if opts.fetch:
os.environ["FETCH_ALL"] = "1"
elif opts.dump:
os.environ["DUMP_ALL"] = "1"
if opts.host:
os.environ["HOST_FILTER"] = "1"
if opts.pause:
os.environ["PAUSE"] = str(opts.pause)
if opts.depth:
os.environ["DEPTH"] = str(opts.depth)
url = args[0]
(q, w) = restore_session(url)
if opts.recipe:
rules = recipe.load_recipe(opts.recipe, url)
else:
pattern = args[1]
rules = recipe.get_recipe(pattern, url)
queue = q or recipe.get_queue(url, mode=fetch.Fetcher.SPIDER)
wb = w or web.Web(url)
except recipe.PatternError, e:
io.write_err(ansicolor.red("%s\n" % e))
sys.exit(1)
except IndexError:
io.opts_help(None, None, None, parser)
main(queue, rules, wb)