-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscrape.py
executable file
·359 lines (274 loc) · 8.5 KB
/
scrape.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
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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
#!/usr/bin/python3
from bs4 import BeautifulSoup as bs
import re
import argparse
import csv
import subprocess
import os
from wait import wait
from lib import quicksort
from progress.bar import Bar
from collections import defaultdict
def get_page_dictio(content, url):
"""
generates a dictionary with important information from the
contents of a (web)page.
"""
if not content:
return None
soup = bs(content, 'html.parser')
ret = {}
try:
_title = soup.title.string
except:
_title = ""
ret['title'] = _title
ret['topic_link'] = get_topic_link(soup)
ret['description'] = get_description(soup)
ret['votes'] = get_votes(soup)
ret['comments'] = comments_dictio(ret)
ret['filename'] = name(url)
ret['url'] = url
# """ also save bandcamp pages as if they were links """
# if not topic_link:
# if 'bandcamp' in url:
# ret['topic_link'] = ret['url']
return ret
def ensure_list(input_):
"""
ensures input_ is a list
if not, wraps it in a list
"""
if isinstance(input_, list):
return input_
else:
return [input_]
def write_csv_output(outputfile, page_list, *args, **kwargs):
"""
writes a list of page dictionaries to a csv file
"""
# default_delim = ','
# if 'delimiter' not in kwargs.keys():
# kwargs['delimiter'] = default_delim
page_list = ensure_list(page_list)
with open(outputfile, 'wt') as csvfile:
csvwriter = csv.writer(csvfile, *args, delimiter=',',
quotechar='"',
quoting=csv.QUOTE_MINIMAL, **kwargs)
for page_ in page_list:
dict_csv_output(page_, csvwriter)
def dict_csv_output(page_dict, csvwriter):
"""
writes csv line for a single page_dict
"""
title = page_dict['title']
votes = page_dict['votes']
comments = page_dict['comments']
topic_link = page_dict['topic_link']
url = page_dict['url']
# title = bytes(title, 'UTF-8')
# votes = bytes(votes, 'UTF-8')
# comments = bytes(comments, 'UTF-8')
csvwriter.writerow([votes, comments, title, topic_link, url])
def get_description(soup):
"""
finds the description attribute of a page, soup
"""
desc = None
tags = soup.find_all('meta')
for tag in tags:
try:
attribute = tag['property']
if attribute == 'og:description':
desc = tag['content']
except KeyError:
pass
return desc
def get_topic_link(soup):
"""
finds the topic link for a page, soup
"""
redditbase = 'http://www.reddit.com'
link = None
tags = soup.find_all('a')
for tag in tags:
try:
attribute = tag['class']
if attribute == ['title', 'may-blank', '']:
link = tag['href']
except KeyError:
pass
if str(link).startswith('/r/'):
link = redditbase + link
return link
def get_votes(soup):
"""
finds number of upvotes in a page, soup
"""
votes = -1
tags = soup.find_all('div')
for tag in tags:
try:
attribute = tag['class']
if attribute == ['score', 'unvoted']:
votes = tag.string
votes = int(votes)
except:
pass
return votes
def comments_dictio(dictio):
return comments(dictio['description'])
def number_from_left(instring):
if not instring:
return None
base = instring.lstrip('0123456789')
nums = instring[:len(instring) - len(base)]
return int(nums), base
def comments(description):
"""
finds number of comments in a page, soup
"""
if not description:
return -1
pat = '(\d+) comments'
match = re.search(pat, description)
if match:
return match.group(1)
else:
return -1
def parse_bookmarks(bookmark_html):
"""
parse bookmark file for links
"""
print("reading from ", bookmark_html)
with open(bookmark_html, 'r') as book:
content = book.read()
soup = bs(content, 'html.parser')
retlinks = []
links = soup.find_all('a')
for link in links:
try:
retlinks.append(link['href'])
except:
print('href error in {}'.format(bookmark_html))
print('> {}'.format(link))
return retlinks
def get_webpage(link, requesttimer, outputfile=None):
"""
downloads webpages
keeps track with requesttimer to not send requests too quickly
"""
if not outputfile:
outputfile = 'index.html'
if not isinstance(outputfile, str):
outputfile = str(outputfile)
if not os.path.isfile(outputfile):
requesttimer.next()
args = ['wget', link, '-O', outputfile, '-o', outputfile + '.log']
_, stderr = subprocess.Popen(args).communicate()
if stderr:
print(stderr)
try:
with open(outputfile, 'r') as ofile:
content = ofile.read()
except:
print("\nerror reading: ", outputfile)
print(link)
return None
return content
def read_csv_to_database(csvfile, *args, **kwargs):
"""
reads list of dictionaries from a csvfile
"""
database = []
with open(csvfile, "r") as filehandle:
csvreader = csv.reader(filehandle, *args,
delimiter=',', quotechar='"',
quoting=csv.QUOTE_MINIMAL, **kwargs)
for row in csvreader:
try:
page_dict = {}
page_dict['votes'] = int(row[0])
page_dict['comments'] = int(row[1])
page_dict['title'] = row[2]
page_dict['topic_link'] = row[3]
page_dict['url'] = row[4]
except:
print("error processing row {}".format(row))
exit(1)
database.append(page_dict)
return database
def remove_duplicates(database):
tups = [tuple(sorted(d.items())) for d in database]
no_dups = [dict(t) for t in set(tups)]
return no_dups
def remove_duplicate_yt(database):
group_dict = group_by_key(database, "topic_link")
_database = []
for k in group_dict.keys():
candidates = group_dict[k]
candidates = quicksort(candidates, lambda x: x['votes'])
_database.append(candidates[0])
return(_database)
def group_by_key(database, key, sort_P=True):
if sort_P:
sort = lambda di: di['topic_link']
database = quicksort(database, sort)
grouped_dict = defaultdict(list)
for item in database:
idx = item[key]
grouped_dict[idx].append(item)
return grouped_dict
def name(url):
return url.replace('/',"").replace('.', "").replace(':',"")
# return url.translate(str.maketrans("", "", "/.:#;"))
def build_database(links, database, max_items=None):
if not max_items:
max_items = len(links)
sort = lambda di: di['votes']
bar = Bar("processing", max=max_items)
requesttimer = wait(2000)
for idx, url in enumerate(links):
if idx >= max_items:
break
# outname = str(idx) + '.html'
# outname = 'dl/' + str(idx) + '.html'
outname = 'dl/' + name(url)
content = get_webpage(url, requesttimer, outname)
dictio = get_page_dictio(content, url)
if dictio:
database.append(dictio)
bar.next()
bar.finish()
return database
def main():
parser = argparse.ArgumentParser(description="reddit scraper, \
sort topic in upvote order")
parser.add_argument('-x', '--extend',
help="extends existing database with new input",
)
parser.add_argument('-o', '--output',
help="output file",
default="data2.csv",
)
args, inputfiles = parser.parse_known_args()
if not inputfiles:
parser.print_usage()
exit(1)
if args.extend:
database = read_csv_to_database(args.extend)
else:
database = []
for inputfile in inputfiles:
links = parse_bookmarks(inputfile)
database = build_database(links, database)
# database = remove_duplicates(database)
print(len(database))
sort = lambda di: di['votes']
database = quicksort(database, sort)
database = remove_duplicate_yt(database)
print(len(database))
write_csv_output(args.output, database)
if __name__ == '__main__':
# test_sort()
main()