-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathRss_crawler.py
232 lines (140 loc) · 7.77 KB
/
Rss_crawler.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
import feedparser
import csv
import getopt
import sys
from _sqlite3 import Row
from datetime import date
from datetime import datetime
from fileinput import filename
from htmlParser import htmlParser
import pickle
import logging
import os.path
import re
import header
from time import mktime
class Crawler:
def __init__(self):
crawlerStartTime = datetime.now()
logging.info( str(crawlerStartTime) + " ############## START CRAWLER #################################################")
self.numOfMsgCrawled = 0
if not os.path.exists(header.outputFilePath):
with open(header.outputFilePath , 'ab') as csvFile:
writer = csv.writer(csvFile, delimiter="," , quotechar='"', quoting=csv.QUOTE_ALL)
writer.writerow(["ArticleTitle" , "Summary" , "Link" , "Timestamp" , "Category" , "Keyword" , "ArticleStory" ])
self.keywordList = self.populateKeywordList()
self.sites = self.populateSiteInformation()
self.siteLastCrawled = self.populateSiteLastCrawled()
self.processSites()
crawlerEndTime = datetime.now()
#TODO Divide by zero exception might occur here, Beware gal
crawlerSpeed = self.numOfMsgCrawled / ( crawlerEndTime - crawlerStartTime ).total_seconds()
logging.info(str(datetime.now()) + " CRAWLER SPEED :: " + str(crawlerSpeed) + " articles/sec" )
logging.info(str(datetime.now()) + " ############## END CRAWLER #################################################")
def __del__(self):
with open(header.siteTimestampPickleFile, "wb") as fp:
pickle.dump(self.siteLastCrawled, fp)
def populateSiteLastCrawled(self):
try:
with open(header.siteTimestampPickleFile) as fp:
siteTimeStampInfo = pickle.load(fp)
return siteTimeStampInfo
except Exception as e:
# Create empty dictionary in case pickle file is not found.
return dict()
def populateKeywordList(self):
keywordList = []
with open(header.keywordFilePath , 'rt') as csvFile:
try:
reader = csv.reader(csvFile)
for row in reader:
keywordList.append(row[0].lower())
finally:
csvFile.close()
return keywordList
# Parse Site Information file for which data is to be crawled.
def populateSiteInformation(self):
sites = []
with open(header.siteInfoFilePath , 'rt') as csvFile:
try:
reader = csv.reader(csvFile)
for row in reader:
isActive = bool(row[1])
if (isActive):
sites.append(row[0])
finally:
csvFile.close()
return sites
def processSites(self):
logging.info(str(datetime.now()) + " ############## START crawling sites #################################################")
for site in self.sites:
logging.info(str(datetime.now()) + " ============= Processing site : " + site + " ======================================")
if site in self.siteLastCrawled:
lastCrawledTimeStamp = self.siteLastCrawled[site]
else:
lastCrawledTimeStamp = datetime.strptime('Jun 1 2005 1:33PM', '%b %d %Y %I:%M%p')
try:
parser_output = feedparser.parse(site)
except Exception as e:
print "Feedparser could not parse " + site
continue
entries = parser_output.entries
# This will update the latest time stamp crawled, and insert the entry if no information was available for this site.
self.siteLastCrawled[site] = datetime.now()
self.processEntries(entries , lastCrawledTimeStamp )
def processEntries(self , entries , timestamp):
# Remove all HTML tags from the text
pattern = re.compile(u'<\/?\w+\s*[^>]*?\/?>', re.DOTALL | re.MULTILINE | re.IGNORECASE | re.UNICODE)
for entry in entries:
title = "NA"
description = "NA"
link = "NA"
published ="NA"
articleContent = "NA"
category = "NA"
if "published" in entry:
published = self.removeNonAscii(entry['published'])
published_parsed_struct = entry['published_parsed']
# In certain instances, published_parsed date is not available, entry is considered valid
if published_parsed_struct == None:
break
published_parsed = datetime.fromtimestamp(mktime(published_parsed_struct))
# Time filter to prevent redundant data collection
if published_parsed < timestamp:
return
if "title" in entry:
title = self.removeNonAscii(entry['title'])
if "description" in entry:
description = pattern.sub(u" " , self.removeNonAscii(entry['description']))
if "category" in entry:
category = self.removeNonAscii(entry['category'])
if "link" in entry:
link = self.removeNonAscii(entry['link'])
httpParserObj = htmlParser(link, 'article')
articleContent = self.removeNonAscii(httpParserObj.fetchText())
#Skip dumping the entry if no keyword is present.
#TODO For training data collection, turning off text filtering. filtering is done on basis of title only
keyword = self.isContainsKeyword(title)
if not(keyword == ""):
return
#self.dumpParsedResult( ['"'+title+'"' , '"'+description+'"' , '"'+link+'"' , '"'+published+'"' , '"'+articleContent+'"' ])
self.dumpParsedResult( [title , description , link , published , category , keyword , articleContent ])
def dumpParsedResult(self , entry_value_list):
self.numOfMsgCrawled = self.numOfMsgCrawled + 1
logging.debug(" Message : " + ', '.join(entry_value_list))
with open(header.outputFilePath , 'ab') as csvFile:
csvWriter = csv.writer(csvFile, delimiter="," , quotechar='"', quoting=csv.QUOTE_ALL)
csvWriter.writerow(entry_value_list)
def removeNonAscii(self , text):
return ''.join([i if ord(i) < 128 else ' ' for i in text])
def isContainsKeyword(self , text):
for keyword in self.keywordList:
if(keyword in text.lower()):
return keyword
return ""
# TODO :
# Filter text : Remove hyperlinks
# Implement Exception Handling
# Implement Timestamp filter, if required
# Parse Site Information file for which data is to be crawled.
# Invoke processSites to start crawling data.