-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclcarhunt.py
336 lines (235 loc) · 7.17 KB
/
clcarhunt.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
#!/usr/bin/env python
import os, urllib, re
import time, sys, math, string
import xml.dom.minidom
from urlparse import urlparse
#global variables
'''
min price of the car
'''
minPrice = 14000
'''
keyPhrases list contains those key words or phrases that we want in search results
'''
keyPhrases = []
'''
postTypes list contains that types of Craigslist ads. Eg, "web" signifies ads appearing in Craigslist's web developer/engineer ads
this value is part of the RSS feed url
'''
postTypes = ['cto']
'''
citiesFile contains a text list with a Craigslist city tags (e.g, "los angeles"), one per line
like the postTypes values, it is used to construct the respective RSS urls
'''
citiesFile = "clcities.txt"
'''
dataFile contains the repository of found links; this file is loaded and updated with each program execution
caution: once it exceeds 50,000 entries, it may be become cumbersome. However, each entry has a time value, so a separate script
can periodically clean the list
'''
dataFile = "cldata.txt"
'''
keyFile contains the list of keys to find (aka cars)
'''
keyFile = "clcars.txt"
'''
cached directory for the intermediate files
'''
cachedir = "cache"
newOutput = []
dataContainer = []
pageContainer = []
urlContainer = []
items = []
entries = []
class clURL:
def __init__( self, url, catagory ):
self.url = url
self.catagory = catagory
class clPageContainer:
def __init__(self, pagedata, catagory):
self.pagedata = pagedata
self.catagory = catagory
########################################################
def readDataFile( filename ):
data = []
try:
data = open(filename,"rU").readlines()
except:
pass
return data
#######################################################
def saveDataFile():
global dataContainer
global newOutput
global dataFile
dataContainer.extend(newOutput)
dataContainer.sort()
data = ""
for item in dataContainer:
if len(item) > 10:
data += item
file = open(dataFile,"w")
print >>file,data
########################################################
def fetchPage( page ):
f = urllib.urlopen(page)
s = f.read()
f.close()
return s
########################################################
def readTheWebContent():
'''
reads the remote feeds and stores them in a list
'''
global pageContainer
global urlContainer
for thisURL in urlContainer:
pageContainer.append( clPageContainer( fetchPage( thisURL.url ), thisURL.catagory) )
########################################################
def parseFeeds():
'''
basic XML parse using minidom
'''
global pageContainer
global entries
global items
for xmlData in pageContainer:
try:
dom = xml.dom.minidom.parseString(xmlData.pagedata)
x = 0
for eNode in dom.getElementsByTagName('item'):
if (len(eNode.getElementsByTagName('description')[0].firstChild.data) > 0):
tl = eNode.getElementsByTagName('link')[0].firstChild.data
tt = eNode.getElementsByTagName('title')[0].firstChild.data
td = eNode.getElementsByTagName('description')[0].firstChild.data
items.append({
'link' : tl,
'title' : tt,
'description': td,
'catagory': xmlData.catagory,
'pagedata': xmlData.pagedata
})
except:
pass
######################################################
def fetchFeedURLS():
"""
builds and puts the feed URLS into a list
"""
global urlContainer
global citiesFile
buf = []
buf += open(citiesFile,"rU").readlines()
for line in buf:
for t in postTypes:
for k in keyPhrases:
#url = "http://" + line.rstrip() + ".craigslist.org/" + t +"/index.rss"
url = "http://" + line.rstrip() + ".craigslist.org/search/" + t +"?minAsk=" + str(minPrice) + "&query=" + k + "&srchType=T&format=rss"
urlContainer.append( clURL( url, k ) ) # currently k is our catagory!
####################################################
def checkIfWanted(title,description):
return True
'''
iterates through the list of keyPhrases. If one is found, the link is used
'''
global keyPhrases
good = False
for ph in keyPhrases:
test = "\s" + ph + "\s"
ck = re.compile(test, re.IGNORECASE)
m1 = ck.findall(title)
m2 = ck.findall(description)
if len(m1) > 0:
return True
if len(m2) > 0:
return True
return good
########################################################
def searchLink(start,end,link):
'''
a very fast binary search of the sorted link array to check if link has already been found
'''
global dataContainer
if end < start:
return -1
length = len(link)
if length > 0:
mid = start +((end-start)/2)
d = dataContainer[mid].split(",")
test = d[0]
if test > link:
return searchLink(start,mid-1,link)
elif link > test:
return searchLink(mid+1,end,link)
else:
return 1
else:
return -1
########################################################
def findLink(l):
global dataContainer
if len(dataContainer) > 1:
return searchLink(0,len(dataContainer)-1,l)
else:
return -1
#######################################################
def processOutput():
out = ""
ind = 0
global dataContainer
global newOutput
global items
newitems = 0
#print "Found", len(items), "cars"
for e in items:
link = e['link']
title = e['title']
desc = e['description']
catagory = e['catagory']
pagedata = e['pagedata']
passed = True #checkIfWanted(title,desc)
if passed == True:
newLink = findLink(link)
if newLink == -1:
ne = link + "," + str(time.time()) + "\n"
newOutput.append(ne)
out += title + "\n"
out += link + "\n"
out += urlparse(link).netloc.split('.')[0] + "\n"
out += "---------------------------\n"
newitems += 1
#cache the pagedata to disk for later scraping
if not os.path.exists(cachedir + "/" + catagory):
os.makedirs(cachedir + "/" + catagory)
flatlink = link.replace('/', "_")
cachedpage = str( cachedir + "/" + catagory + "/" + flatlink)
f = file( cachedpage, "w" )
f.write( fetchPage( link ) )
f.close()
return out, newitems
#####################################################
#main
#read existing storage file
dataContainer += readDataFile( dataFile )
#read the key phrases
keyPhrases = readDataFile( keyFile )
#web traffic
fetchFeedURLS()
readTheWebContent()
#post processing
parseFeeds()
out, newitems = processOutput()
out = out.encode('utf-8')
#store the new state
saveDataFile()
'''
output is generated only if we have new entries. If executed via a cron job, the output will be sent as a system email
the time values in the output are useful to gauge if the data file is becoming unwieldly.
The run-time for this script is about 1.6 seconds per feed, and almost all of that is accessing the url.
'''
if len(newOutput) > 0:
print newitems, "new cars"
print len(items), "found cars"
print out
sys.exit()