-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathscraper.py
436 lines (278 loc) · 11 KB
/
scraper.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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
#! /usr/bin/env python
# -*- coding: UTF-8 -*-
"""
Scraper
==========
Given, the ANDROID-APP-URL, this module is meant to be able
to extract an agreed upon set of features about the app
- [x] Name
- [x] Company
- [x] AppCategory
- [x] AppId
- [x] AppVer
- [x] Price
- [x] Rating
- [
(OneStarRating, OneStarRatingCount),
(TwoStarRating, TwoStarRatingCount)
(ThreeStarRating, ThreeStarRatingCount)
(FourStarRating, FourStarRatingCount)
(FiveStarRating, FiveStarRatingCount)
]
- [x] Total Reviewers
- [-] PlusOneCount
- [x] CountOfScreenShots
- [x] Description
- [x] Installs
- [x] ContentRating
- [x] SimilarApps:
set([SimAppId1, SimAppId2, ..])
- [x] MoreAppsFromDev
set([OtherAppId1, OtherAppId2, .. ])
- [x] User Reviews
[
(Review Heading, Review Text),
(Review Heading, Review Text),
(Review Heading, Review Text),
...
]
- [x] Developer Website URL
- [x] Developer Email
- [x] Privacy Policy URL
python_version = "Python 2.7.5 :: Anaconda 1.6.1 (x86_64)"
"""
from __future__ import division
from optparse import OptionParser
from bs4 import BeautifulSoup
from urllib import urlopen
from HTMLParser import HTMLParser
# from lxml import etree
from pprint import pprint
import json
import time
# reference: http://stackoverflow.com/questions/753052/strip-html-from-strings-in-python
# To strip html tags
class MLStripper(HTMLParser):
def __init__(self):
self.reset()
self.fed = []
def handle_data(self, d):
self.fed.append(d)
def get_data(self):
return ''.join(self.fed)
def strip_tags(html):
s = MLStripper()
s.feed(html)
return s.get_data()
def getUserInput():
optionparser = OptionParser()
optionparser.add_option('-u', '--url', dest='appurl')
optionparser.add_option('-f', '--file', dest='applist')
optionparser.add_option('-t', '--time', dest='apptime')
optionparser.add_option('-e', '--export', dest='exportfilename')
(option, args) = optionparser.parse_args()
if not option:
return optionparser.error('data not provided.\n Usage: --url="path.to.appurl", --file to "path.to.file"')
return { 'url' : option.appurl, 'file' : option.applist, 'time' : option.apptime, 'name' : option.exportfilename }
def handleDataError(raw):
"""
Handle raw values which could be empty or non existent or illformatted
"""
try:
clean = strip_tags(str(raw[0]))
except:
clean = 'N.A.'
return clean
def getAppFeatures(app):
"""
Given the Application URL, Extract the desired features
"""
pageHtml = urlopen(app).read()
# pageTree = etree.parse(pageHtml)
pageSoup = BeautifulSoup(pageHtml, 'html5')
# Application Id
appIdStr = app.split('?')[1]
appId = appIdStr[3:]
# Application Description
appDescHTML = pageSoup.findAll('div', {"class":"app-orig-desc"})
appDesc = appDescHTML[0].get_text()
# Application Company
appCompHTML = pageSoup.findAll('a', {"itemprop":"name"})
appComp = appCompHTML[0].get_text()
# Application Name
appNameHTML = pageSoup.findAll('div', {"itemprop":"name"})
appName = appNameHTML[0].get_text()
# Developer details
appDevDetailSoup = pageSoup.find_all('a', attrs={'class':'dev-link'})
appDevDetail = {}
appDevDetail['devurl'] = 'N.A.'
appDevDetail['devmail'] = 'N.A.'
appDevDetail['devprivacyurl'] = 'N.A.'
for elem in appDevDetailSoup:
# print "dev-link", elem['href'], elem.get_text()
elemText = elem.get_text()
elemText = str(elemText.strip())
if elemText == "Visit Developer's Website":
devurl = elem['href'].split('?')
appDevDetail['devurl'] = devurl[1][2:]
if elemText == "Email Developer":
devmail = elem['href'].split(':')
appDevDetail['devmail'] = devmail[1]
if elemText == "Privacy Policy" :
devprv = elem['href'].split('?')
appDevDetail['devprivacyurl'] = devprv[1][2:]
# pprint(appDevDetail)
appPrice = getAppPrice(pageSoup) # Application Price
appRating = getAppRating(pageSoup) # Application Rating
appReviewers = getTotalReviewers(appRating) # Total Reviewers
appCat = pageSoup.find(itemprop='genre').get_text() # Application Category
appVerElem = pageSoup.find_all('div', attrs={'itemprop':'softwareVersion'})
appVer = handleDataError(appVerElem)
appInstallElem = pageSoup.find_all('div', attrs={'itemprop':'numDownloads'})
appInstall = handleDataError(appInstallElem) #Application Installs
appContentRatingElem= pageSoup.find_all('div', attrs={'itemprop':'contentRating'})
appContentRating = handleDataError(appContentRatingElem) #Application Content Rating
appSizeElem = pageSoup.find_all('div', attrs={'itemprop':'fileSize'})
appSize = handleDataError(appSizeElem) #Application Silze
appScreenElem = pageSoup.find_all('img', attrs={'itemprop':'screenshot'})
# pprint(appScreenElem)
appScreenCount = len(appScreenElem)
appReviewElem = pageSoup.find_all('div', attrs={'class':'review-text'})
# Get App Reviews
appReviews = []
for elem in appReviewElem:
revtitle = elem.span.get_text()
elem.span.decompose() # to remove the title
revtext = elem.get_text()
appReviews.append((revtitle, revtext))
# Get Similar and Dev app list
# appRecos = pageSoup.find_all('div', attrs={'class':'details-section recommendation '})
appRecoElems = pageSoup.select('a[href^="/store/apps/details?id="]')
# print "recommendation:", appRecos
appSim = [] # apps that are similar and hence recommended
appDev = [] # apps from same developer
for app in appRecoElems:
if '&' not in app['href']:
appPathStr = app['href'].split('=')
appPath = appPathStr[1]
currentAppIdStr = appId.split('.')
otherAppIdStr = appPath.split('.')
if (currentAppIdStr[0] == otherAppIdStr[0]) & (currentAppIdStr[1] == otherAppIdStr[1]):
## apps from the same developer
appDev.append(appPath)
else:
appSim.append(appPath)
appDetails = {}
appDetails['id'] = appId.strip()
appDetails['name'] = appName.strip()
appDetails['category'] = appCat.strip()
appDetails['size'] = appSize.strip()
appDetails['price'] = appPrice
appDetails['description'] = appDesc.strip()
appDetails['company'] = appComp.strip()
appDetails['version'] = appVer.strip()
appDetails['install'] = appInstall.strip()
appDetails['contentRating'] = appContentRating.strip()
appDetails['rating'] = list(set(appRating))
appDetails['totalReviewers'] = appReviewers
appDetails['screenCount'] = appScreenCount
appDetails['reviews'] = appReviews
appDetails['devurl'] = appDevDetail['devurl']
appDetails['devmail'] = appDevDetail['devmail']
appDetails['devprivacyurl'] = appDevDetail['devprivacyurl']
appDetails['moreFromDev'] = 'None' if (len(set(appDev)) == 0) else list(set(appDev))
appDetails['similar'] = 'None' if (len(set(appSim)) == 0) else list(set(appSim))
return appDetails
def getAppPrice(pageSoup):
"""
Given soup of the html page, extract the price of the app
"""
priceSoup = pageSoup.find('span', {"class" : "price", "class":"buy"})
priceList = list(priceSoup.contents)
price = priceList[-2].get_text().strip()
# print "price", price
if price == 'Install':
priceVal = 0.0
else:
priceVal = float(str(price[1:4])) # since first character is currrency
return priceVal
def getAppRating(pageSoup):
"""
Given the page soup, extract the app ratings and the count of
people who gave those ratings
"""
appRatingSoup = pageSoup.find_all('div', {'class':'rating-bar-container'})
appRating = []
for ratingContainer in appRatingSoup:
# print type(ratingContainer)
ratElem = ratingContainer.find_all("span", attrs={"class":"bar-label"})
ratcountElem = ratingContainer.find_all("span", attrs={"class":"bar-number"})
rat = strip_tags(str(ratElem[0]))
ratcountraw = strip_tags(str(ratcountElem[0]))
ratcount = formatStrToNum(ratcountraw)
appRating.append((rat, ratcount))
return appRating
def getTotalReviewers(ratingTup):
"""
Given a tuple of ratings, sum the count of Reviewers
"""
totalReviewers = 0
for r in ratingTup:
totalReviewers += r[1]
return totalReviewers
def formatStrToNum(rawnum):
"""
Handle different forms of string values that need to be converted to
numbers
1,000 -> 1000
"""
if ',' in rawnum:
rawnum = rawnum.replace(',', '')
return int(rawnum)
def main():
print __doc__
relaxtime = 5
userInput = getUserInput()
filename = 'rawdata' # default file name for exporting
if userInput['name'] != None:
filename = userInput['name']
exportFileAll = 'exports/' + filename + '_all.json'
exportFileReviews = 'exports/' + filename + '_reviews.json'
if userInput['time'] != None:
relaxtime = userInput['time']
if userInput['file'] == None:
## Single url input given
features = getAppFeatures(userInput['url'])
pprint(features)
else:
## File input given
## run through the list of url and
with open(userInput['file']) as f:
fileTxt = f.readlines()
allRows = []
allRevs = []
fileProcessed = 0
for line in fileTxt:
fileProcessed += 1
# Only read lines that do not start with # so we can comment
# apps whose urls have been taken down
if line.startswith('#'):
print "Skipping %d app" % (fileProcessed)
else:
features = getAppFeatures(line)
allRows.append(features)
time.sleep(relaxtime) ## pause for next request
revfeatures = {}
revfeatures['appId'] = features['id']
revfeatures['reviews'] = features['reviews']
revfeatures['moreFromDev'] = features['moreFromDev']
revfeatures['similar'] = features['similar']
allRevs.append(revfeatures)
print "Finished processing %d / %d app urls" % (fileProcessed, len(fileTxt))
with open(exportFileAll, 'w+') as fp:
json.dump(allRows, fp, sort_keys=True)
print "Exported the data to: \t %s" % (exportFileAll)
with open(exportFileReviews, 'w+') as fp:
json.dump(allRevs, fp, sort_keys=True)
if __name__ == '__main__':
main()