-
Notifications
You must be signed in to change notification settings - Fork 0
/
yelpSupplementalScraper2.py
289 lines (251 loc) · 11.3 KB
/
yelpSupplementalScraper2.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
import pickle
import sys
import time
import traceback
from urllib2 import urlopen
from bs4 import BeautifulSoup
from progressbar import *
from specialFunctions import NYCzips, getTags, getPercentDiff,YelpRestaurant,CGRestaurant,getYelpURL2, findRestMatch
verbose = False
zipContinue = False
indexContinue = False
programfail=False
try:
if sys.argv[1] == '--verbose':
verbose = True
if int(sys.argv[2]):
zipContinue = sys.argv[2]
if int(sys.argv[3]):
indexContinue = sys.argv[3]
except:
pass
def ratingRound(numstr):
last = int(numstr[-1])
if last < 3:
return float(numstr[:2]+str(0))
elif last < 8:
return float(numstr[:2]+str(5))
else:
last = 0
return float(str(float(numstr)+1.0)[:2]+str(0))
outFile = type(file)
goodlist = [[0,0]]
def sighandler(signal,frame):
if programfail:
print "Code fail"
else:
print "Ctrl+C pressed: storing Yelp data"
pickle.dump(goodlist,outFile)
print 'Program halted at ZIP: %d; INDEX: %d' % (goodlist[0][0],goodlist[0][1])
outFile.close()
print 'Everything pickled and saved! YAY!'
sys.exit(1)
exit(-1)
uncatchable = ['SIG_DFL','SIGSTOP','SIGKILL']
for i in [x for x in dir(signal) if x.startswith("SIG")]:
if not i in uncatchable:
signum = getattr(signal,i)
signal.signal(signum,sighandler)
checked = 0
failPriceCount = 0
failReviewCount = 0
totalGoodCount = 0
zipRestCount = {}
failBoth = 0
failNoMatch = 0
bothTest = 0
souper = BeautifulSoup('html')
widgets = ['Running: ', Percentage(), ' ',
Bar(marker='0',left='[',right=']'),
' ', Timer()]
pbar = ProgressBar(widgets=widgets, maxval=len(NYCzips))
pbar.start()
try:
for indexz,zipcode in enumerate(NYCzips[:11]):
#if zipcode < zipContinue:
#continue
print 'Zip: %d ==============================================================================' % (zipcode)
goodcount = 0
locStart = 0
goodlist = [[zipcode,0]]
zipRestCount[zipcode] = 0
try:
exec("restartFile=open('%s','r')" % (str(zipcode)+'results2Yelped'))
print 'Found a Yelp! results file for %d. Checking to see if we need to continue...' % (zipcode)
checkpoint = pickle.load(restartFile)
restartFile.close()
if checkpoint[0][0] == zipcode:
locStart = checkpoint[0][1]
print 'Yep. We need to continue from index ' + str(locStart)
goodlist = checkpoint
checked+=locStart
totalGoodCount+=len(checkpoint[1:])
zipRestCount+=len(checkpoint[1:])
else:
print 'Nope. This file looks complete. Moving on...'
exec("inFile=open('%s','r')" % (str(zipcode)+'results2woClosed'))
checked+=len(pickle.load(inFile))
totalGoodCount+=len(checkpoint)
zipRestCount[zipcode] = len(checkpoint)
inFile.close()
continue
except:
pass
exec("inFile=open('%s','r')" % (str(zipcode)+'results2woClosed'))
exec("outFile=open('%s','w')" % (str(zipcode)+'results2Yelped'))
locations = pickle.load(inFile)
inFile.close()
for index,location in enumerate(locations[locStart:]):
#if (zipcode == zipContinue and index < indexContinue):
#continue
index = index + locStart
goodlist[0][1] = index
pbar.update(indexz+1)
soup = BeautifulSoup(location,'xml')
cgRest = CGRestaurant(soup)
print time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime()) + ' Yelp Page Grab'
try:
yelpSoup = BeautifulSoup(urlopen(getYelpURL2(cgRest.name,cgRest.zip)))
except:
yelpSoup = BeautifulSoup(urlopen(getYelpURL2(cgRest.name,cgRest.zip)))
time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime()) + ' Yelp Page Grab'
yelpRest = findRestMatch(cgRest, yelpSoup,checked,totalGoodCount,index)
#Look at next page for more hits if not finding enough matches
cgRest.fix_types()
if yelpRest:
if verbose:
print '\n\n\n!!!!!!!!!!!!'
print 'MATCH FOUND'
print '!!!!!!!!!!!!'
print '(((((((((( ' + str([cgRest.desc]) + ':::' + str([yelpRest.desc]) + ' ))))))))))'
yelpRest.fix_types()
if yelpRest.name:
cgRest.name = yelpRest.name
cgRest.categoryTags = cgRest.categoryTags + yelpRest.categoryTags
#check if yelpRest has rating, user_review_count, and price data
if yelpRest.price in ['$','$$','$$$','$$$$'] and yelpRest.rating: ###yelp restaurant has price and rating data
print 'IIIIIIIIIIIIIIIIIII YELP HAS PRICE IIIIIIIIIIIIIIIIIIIII'
if cgRest.price in ['$','$$','$$$','$$$$'] and cgRest.rating:
cgRest.rating = ( (cgRest.rating*float(cgRest.reviewCount))+(yelpRest.rating*float(yelpRest.reviewCount))) / (float(cgRest.reviewCount)+float(yelpRest.reviewCount))
cgRest.rating = ratingRound('{0:.1f}'.format(cgRest.rating))
cgRest.reviewCount = cgRest.reviewCount + yelpRest.reviewCount
elif (not cgRest.price in ['$','$$','$$$','$$$$']) and (not cgRest.rating):
cgRest.price = yelpRest.price
cgRest.rating = yelpRest.rating
cgRest.reviewCount = yelpRest.reviewCount
elif (not cgRest.price in ['$','$$','$$$','$$$$']):
cgRest.price = yelpRest.price
cgRest.rating = ( (cgRest.rating*float(cgRest.reviewCount))+(yelpRest.rating*float(yelpRest.reviewCount))) / (float(cgRest.reviewCount)+float(yelpRest.reviewCount))
cgRest.rating = ratingRound('{0:.1f}'.format(cgRest.rating))
cgRest.reviewCount = cgRest.reviewCount + yelpRest.reviewCount
else:
cgRest.rating = yelpRest.rating
cgRest.reviewCount = yelpRest.reviewCount
elif yelpRest.rating: ###yelp restaurant is missing price data, has rating data
print 'IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII YELP DOESNT HAVE PRICE'
if cgRest.price in ['$','$$','$$$','$$$$'] and cgRest.rating:
cgRest.rating = ( (cgRest.rating*float(cgRest.reviewCount))+(yelpRest.rating*float(yelpRest.reviewCount))) / (float(cgRest.reviewCount)+float(yelpRest.reviewCount))
cgRest.rating = ratingRound('{0:.1f}'.format(cgRest.rating))
cgRest.reviewCount = cgRest.reviewCount + yelpRest.reviewCount
elif cgRest.price in ['$','$$','$$$','$$$$']:
cgRest.rating = yelpRest.rating
cgRest.reviewCount = yelpRest.reviewCount
else:
print 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX NEITHER CG OR YELP HAS PRICE DATA'
if cgRest.price in ['$','$$','$$$','$$$$'] and cgRest.rating and cgRest.reviewCount >= 10 and cgRest.zip: #if restaurant
goodlist.append(cgRest.useful_data())
zipRestCount[zipcode]+=1
goodcount+=1
totalGoodCount+=1
if verbose:
print '++++++++++++++PASS!:::::::::Running Count = ' + str(totalGoodCount) + '; Price: ' + str(cgRest.price) +', Rating: ' + str(cgRest.rating) + ', Rev Count: ' + str(cgRest.reviewCount)
try:
if (not cgRest.price in ['$','$$','$$$','$$$$']):
failPriceCount+=1
if verbose:
try:
print 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX FAIL, MISSING PRICE:::::::::Running Count = ' + str(failPriceCount) + ' price: ' + cgRest.price + ' ' + str(cgRest.desc)
except:
print 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX FAIL, MISSING PRICE:::::::::Running Count = ' + str(failPriceCount) + ' ' + str(cgRest.desc)
except Exception, e:
print "[-] Error = "+str(e)
print 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX FAILED PRICE CHECK FAIL COUNT: price---> ' + cgRest.price
failPriceCount+=1
if verbose:
print 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX FAIL, MISSING PRICE:::::::::Running Count = ' + str(failPriceCount) + ' ' + str(cgRest.desc)
try:
if (not cgRest.rating) or cgRest.reviewCount < 10:
try:
print 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX ' + str(cgRest.rating) + ' ' + str(cgRest.reviewCount) + ' ' + str(yelpRest.rating) + ' ' + str(yelpRest.reviewCount) + ' RATING OR REVIEW COUNT FAIL'+ str(cgRest.desc)
except:
print 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX ' + str(cgRest.rating) + ' ' + str(cgRest.reviewCount) + ' ' + ' RATING OR REVIEW COUNT FAIL' + ' ' + str(cgRest.desc)
failReviewCount+=1
if verbose:
print 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX FAIL on LOW REVIEWS: Review Count = '+ str(cgRest.reviewCount) + ' ::::::Running Count = ' + str(failReviewCount) + ' ' + str(cgRest.desc)
if bothTest != failPriceCount:
failBoth+=1
except Exception, e:
print "[-] Error = "+str(e)
print 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX FAILED LOW REVIEW FAIL COUNT: ---> rating: ' + str(cgRest.rating) + ', reviewCount: ' + str(cgRest.reviewCount) + ' ' + str(cgRest.desc)
failReviewCount+=1
if verbose:
print 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX FAIL on LOW REVIEWS: Review Count = '+ str(cgRest.reviewCount) + ' ::::::Running Count = ' + str(failReviewCount) + ' ' + str(cgRest.desc)
if bothTest != failPriceCount:
failBoth+=1
bothTest = failPriceCount
goodlist[0][1]+=1
checked+=1
del cgRest
del yelpRest
print 'ZIP SUMMARY:'
print '---------------------------------'
print '%d restaurants checked in zip, total checked: %d' % (goodlist[0][1]-1,checked)
print '%d restaurants passed' % (totalGoodCount)
print '%d total failed' % (goodlist[0][1]-goodcount)
print '%d restaurants failed for not having a price' % abs(failPriceCount-failBoth)
print '%d restaurants failed for not having enough reviews (10 or more)' % abs(failReviewCount-failBoth)
print '%d restaurants failed for not having a price or enough reviews' % (failBoth)
print '======================================================================================================================'
goodlist.pop(0)
print goodlist
print '======================================================================================================================\n'
pickle.dump(goodlist,outFile)
outFile.close()
del goodlist
except Exception, e:
print "[-] Error = "+str(e)
exc_type, exc_value, exc_traceback = sys.exc_info()
print "*** print_tb:"
traceback.print_tb(exc_traceback, limit=1, file=sys.stdout)
print "*** print_exception:"
traceback.print_exception(exc_type, exc_value, exc_traceback,limit=2, file=sys.stdout)
print "*** print_exc:"
traceback.print_exc()
print "*** format_exc, first and last line:"
formatted_lines = traceback.format_exc().splitlines()
print formatted_lines[0]
print formatted_lines[-1]
print "*** format_exception:"
print repr(traceback.format_exception(exc_type, exc_value,exc_traceback))
print "*** extract_tb:"
print repr(traceback.extract_tb(exc_traceback))
print "*** format_tb:"
print repr(traceback.format_tb(exc_traceback))
print "*** tb_lineno:", exc_traceback.tb_lineno
print '==============================================='
print ' Finished. Printing Summary'
for zipcode in zipRestCount:
print str(zipcode) + ':\t' + str(zipRestCount[zipcode])
print '==============================================='
print 'Total: %d' % (totalGoodCount)
sighandler('signal','frame')
try:
pbar.finish()
except:
pass
print '==============================================='
print ' Finished. Printing Summary'
for zipcode in zipRestCount:
print str(zipcode) + ':\t' + str(zipRestCount[zipcode])
print '==============================================='
print 'Total: %d' % (totalGoodCount)