-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprocess_homepage.py
303 lines (263 loc) · 9.4 KB
/
process_homepage.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import re
import os
import argparse
import csv
import logging
import string
import gzip
from ftfy import fix_text
from zipfile import ZipFile, ZIP_DEFLATED
import newspaper
from newspaper import Article
from bs4 import BeautifulSoup
from scraper import SimpleScraper, SeleniumScraper
from datetime import datetime
from configparser import ConfigParser
from notification import Notification
from glob import glob
"""
CSV with following fields:
date, time, src, url, text of the link,
title of the article, path to local content file
* Multiple folders --- one for each news org and
containing content of the files in a standard format
(after newspaper package), stripped off all HTML,
name of each file = three_letter_src_name_date_time_order
"""
CSV_HEADER = ['date', 'time', 'src', 'order', 'url', 'link_text', 'homepage_keywords']
NEWSPAPER_HEADER = ['path', 'title', 'text', 'top_image', 'authors',
'summary', 'keywords']
MAX_RETRY = 5
LINKS_CONF = {'fox':
[('20160101_000000',
{'css': ['a'],
're': [r'.*/\d{4}/\d{2}/\d{2}/.*html$'
],
'base': ''
}
)],
'google':
[('20160101_000000',
{'css': ['a', {'class': 'article'}],
're': [r'.*'],
'base': ''
}
)],
'hpmg':
[('20160101_000000',
{'css': ['a'],
're': [r'.*/entry/.*'
],
'base': ''
}
)],
'nyt':
[('20160101_000000',
{'css': ['a'],
're': [r'.*/\d{4}/\d{2}/\d{2}/.*html$'
],
'base': ''
}
)],
'usat':
[('20160101_000000',
{'css': ['a'],
're': [r'/story/.*/\d{4}/\d{2}/\d{2}/.*/$'
],
'base': 'http://www.usatoday.com'
}
)],
'wapo':
[('20160101_000000',
{'css': ['a'],
're': [r'https://www.washingtonpost.com/(.*?)/.*/\d{4}/\d{2}/\d{2}/.*'
],
'base': ''
}
)],
'wsj':
[('20160101_000000',
{'css': ['a'],
're': [r'http://www.wsj.com/.*\d{9,}$'
],
'base': ''
}
)],
'yahoo':
[('20160101_000000',
{'css': ['a'],
're': [r'/news/.*html.*'
],
'base': 'https://www.yahoo.com'
}
)],
}
def setup_logger():
""" Set up logging
"""
logfilename = "process-homepage.log"
logging.basicConfig(level=logging.INFO,
format='%(asctime)s %(levelname)-8s %(message)s',
datefmt='%m-%d %H:%M',
filename=logfilename,
filemode='a')
console = logging.StreamHandler()
console.setLevel(logging.INFO)
formatter = logging.Formatter('%(message)s')
console.setFormatter(formatter)
logging.getLogger('').addHandler(console)
return logfilename
def remove_special_chars(text):
"""remove all special characters except the period (.)
and question mark (?)
for instance, ">", "~", ", $, |, etc.
"""
schars = ''.join([a for a in string.punctuation if a not in ".?"])
text = re.sub('[%s]' % re.escape(schars), '', text)
return text
def clean_text(text):
text = fix_text(text)
text = ' '.join(text.split('\n'))
text = remove_special_chars(text)
return text
def process_newspaper(r):
retry = 0
while retry < MAX_RETRY:
try:
logging.info("Processing URL {0:s}".format(r['url']))
article = Article(url=r['url'])
article.download()
dt = r['date'].replace('-', '') + r['time'].replace(':', '')
name = '{0!s}_{1!s}_{2:d}.html'.format(r['src'], dt, r['order'])
outdir = './news-homepage/{0!s}'.format(r['src'])
if not os.path.exists(outdir):
os.mkdir(outdir)
filename = os.path.join(outdir, name)
with open(filename, 'w', encoding='utf-8') as f:
f.write(article.html)
r['path'] = filename
article.parse()
r['text'] = clean_text(article.text)
r['top_image'] = article.top_image
r['authors'] = '|'.join(article.authors)
r['title'] = clean_text(article.title)
#print(article.images)
#print(article.movies)
article.nlp()
r['summary'] = clean_text(article.summary)
r['keywords'] = '|'.join(article.keywords)
break
except Exception as e:
logging.error(e)
retry += 1
logging.warn("Retry #{0:d}".format(retry))
return r
def write_to_csv(writer, results, with_text=False):
for i, r in enumerate(results):
r['order'] = i + 1
if with_text:
r = process_newspaper(r)
# FIXME: check and try to fix URL if no result from newspaper
if 'title' not in r:
# strip off URL params
r['url'] = r['url'].split('?')[0]
r['order'] = int(r['order'])
print(r['url'])
r = process_newspaper(r)
if 'title' not in r:
# try original URL directly
split_url = r['url'].split('http://')
if len(split_url) > 1:
r['url'] = 'http://' + split_url[-1]
print("New URL: %s" % r['url'])
r = process_newspaper(r)
r['link_text'] = clean_text(r['link_text'])
writer.writerow(r)
def process_homepage(src, d, t, fn, conf):
print("Processing: '{0:s}'".format(fn))
if fn.endswith('.gz'):
try:
with gzip.open(fn, 'rb') as f:
html = f.read()
except:
print("Cannot open file '{0:s}".format(fn))
html = ''
else:
with open(fn, encoding='utf-8') as f:
html = f.read()
try:
article = Article(url='')
article.set_html(html)
article.parse()
article.nlp()
keywords = '|'.join(article.keywords)
except Exception as e:
keywords = ''
soup = BeautifulSoup(html, 'lxml')
links = soup.find_all(*conf['css'])
results = set()
for r in conf['re']:
rc = re.compile(r)
for a in links:
try:
href = a['href']
if rc.match(href):
url = conf['base'] + href
text = a.text.strip()
results.add((text, url))
except:
pass
new_results = []
for text, url in results:
new_results.append({'src': src,
'date': d,
'time': t,
'link_text': text,
'url': url,
'homepage_keywords': keywords})
return new_results
if __name__ == "__main__":
logfilename = setup_logger()
parser = argparse.ArgumentParser(description='Parse Homepage and Download Article')
parser.add_argument('directory', help="Scraped homepages directory")
parser.add_argument('-o', '--output', default='output-homepage.csv',
help='Output file name')
parser.add_argument('--with-header', dest='header', action='store_true',
help='Output with header at the first row')
parser.set_defaults(header=False)
parser.add_argument('--with-text', dest='with_text', action='store_true',
help='Download the article text')
parser.set_defaults(with_text=False)
args = parser.parse_args()
logging.info(args)
# to keep scraped data
if not os.path.exists('./news-homepage'):
os.mkdir('./news-homepage')
with open(args.output, 'w', encoding='utf-8', newline='') as f:
writer = csv.DictWriter(f, fieldnames=CSV_HEADER + NEWSPAPER_HEADER,
dialect='excel', quoting=csv.QUOTE_NONNUMERIC)
if args.header:
writer.writeheader()
print(LINKS_CONF.keys())
for fn in (glob(args.directory + '/*.html') +
glob(args.directory + '/*.gz')):
m = re.match(r'(.*)_(\d{8})_?(\d{6})\.html(?:\.gz)?',
os.path.basename(fn))
if m:
src = m.group(1).split('_')[0]
d = m.group(2)
t = m.group(3)
else:
print("Cannot match file name, skipped '{0:s}'".format(fn))
continue
dt = '_'.join([d, t])
if src in LINKS_CONF.keys():
for i in LINKS_CONF[src]:
if dt >= i[0]:
results = process_homepage(src, d, t, fn, i[1])
write_to_csv(writer, results, args.with_text)
break
logging.info("Done")