-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscrape.py
2491 lines (2284 loc) · 81.4 KB
/
scrape.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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Sample thingy
def get_url_text(url):
#gets the source of a URL in xml tree format
url_hash = hashlib.sha1(url).hexdigest()
#load from disk if it exists, if not fetch and store and disk
try:
#raise IOError()
f = codecs.open("%s.txt" % url_hash, 'r', encoding="latin-1")
x = f.read()
except IOError:
printc("WTF!", 1)
resp = urllib2.urlopen(url).read()
f = open("%s.txt" % url_hash, 'w')
f.write(resp)
x = resp
return fromstring(unicode(x))
#########################################################
#Start of the test scripts
#########################################################
from pyquery import PyQuery as pq
import urllib2
import lxml
import hashlib
import os
import csv
import re
from time import ctime as now
from time import time
from datetime import timedelta as td
from unicodedata import normalize as un
def writelog(entry,filename='log'):
f = open(filename,'a')
f.write(now()+" > ")
f.write(entry)
f.write('\n')
f.close()
def mobylistcheck():
url = "http://www.mobygames.com/browse/games/list-games/"
y = pq(url)
number = y(".mobHeader .mobHeaderItems").text()
print "Number of games : " + number[-6:-1]
def initmobylist(list=30657):
"""Initialize moby list"""
global num
num = range(0,list+1,25)
print "Tracking "+str(list)+" games in moby database"
print "Last page starts with : " + str(num[-1])
'''d = pq("http://www.mobygames.com/browse/games/offset,"+str(x)+"/so,0a/list-games/")
test = [x.attrib["href"] for x in d("#mof_object_list tbody a")]
for x in num:
y = pq("http://www.mobygames.com/browse/games/offset,"+str(x)+"/so,0a/list-games/")
scrap.append(y)
print "done batch "+str(x)
'''
####
#### Grab moby URLs of individual Games
####
def mobyscrapepage():
"""Populate scrap list with URLs of individual games"""
print ("Populating moby game list...")
global scrap
scrap = []
# linecount = 0
for x in num:
url = "http://www.mobygames.com/browse/games/offset,"+str(x)+"/so,0a/list-games/"
url_hash = hashlib.sha1(url).hexdigest()
try:
f=open("cache/%s.txt" % url_hash, 'r')
x=f.read()
y = pq(x)
grab = [z.attrib["href"] for z in y("#mof_object_list tbody a")]
for line in grab:
if line not in scrap:
if "/game/" in line:
scrap.append(line)
# print ("added "+str(line))
# linecount += 1
except IOError:
print ("scraping new html of "+str(x))
resp = urllib2.urlopen(url).read()
f = open("cache/%s.txt" % url_hash, 'w')
f.write(resp)
print ("done "+str(x))
print ("Finished populating moby game list")
#######
# update moby game browser cache
#######
def updatemobycache():
"""update moby gamebrowser listing"""
writelog("starting moby gamebrowser listing update")
start = time()
count = 0
errcount = 0
updateerr=[]
for x in num:
try:
url = "http://www.mobygames.com/browse/games/offset,"+str(x)+"/so,0a/list-games/"
url_hash = hashlib.sha1(url).hexdigest()
print ("removing "+url)
os.remove("cache/%s.txt" % url_hash)
count += 1
print ("removed "+url)
except:
errcount += 1
updateerr.append(url)
try:
webscrape(url)
except urllib2.URLError, (err):
print ("URL error(%s)" % (err))
print ("Retrying...")
webscrape(url)
except:
raise
if errcount:
print ("Errors: "+str(errcount))
end = time()
elapse = str(td(seconds = end - start))
writelog("Complete mobygame browser listing update in " + elapse)
print "Time elapsed " + elapse
##########
#scrape moby individial game pages
##########
def scrapepage1():
"""scrape individual game page"""
writelog("starting moby individual game page scrape")
start = time()
#count=0
for x in scrap:
url = "http://www.mobygames.com"+str(x)
url_hash = hashlib.sha1(url).hexdigest()
try:
f=open("cache/%s.txt" % url_hash, 'r')
# x=f.read()
# y = pq(x)
# print (str(count)+" | "+x)
#count += 1
except IOError:
print ("scraping new html of "+url)
resp = urllib2.urlopen(url).read()
f = open("cache/%s.txt" % url_hash, 'w')
f.write(resp)
print ("done "+str(x))
#count += 1
except:
end = time()
elapse = str(td(seconds = end - start))
writelog("Error, process stopped after: "+ elapse)
print "Error Time elapsed: " + elapse
raise
end = time()
elapse = str(td(seconds = end - start))
writelog("Completed individual game page scrape in " + elapse)
print "Time elapsed " + elapse
######
#scrape credits page
######
def scrapepage2():
"""scrape credit page"""
writelog("starting moby game credit page scrape")
start = time()
# count = 0
for x in scrap:
url = "http://www.mobygames.com"+str(x)+"/credits"
url_hash = hashlib.sha1(url).hexdigest()
try:
f=open("cache/%s.txt" % url_hash, 'r')
# x=f.read()
# y = pq(x)
# print (str(count)+" | "+x+"/credits")
# count += 1
except IOError:
print ("scraping new html of "+url)
resp = urllib2.urlopen(url).read()
f = open("cache/%s.txt" % url_hash, 'w')
f.write(resp)
print ("done "+url)
# count += 1
except:
end = time()
elapse = str(td(seconds = end - start))
writelog("Error, credit scrape process stopped after: "+ elapse)
print "Error Time elapsed: " + elapse
raise
end = time()
elapse = str(td(seconds = end - start))
writelog("Completed credit scrape in " + elapse)
print "Time elapsed " + elapse
######
# Grab platform page info from each tech page
######
def mobygrabplat(listing):
"""Grab techinfo individual platform pages"""
global mbtechplatind
mbtechplatind = []
setlisting = set(listing)
for x in setlisting:
url = x
gamedet = []
page = pq(htmlcache(url))
page.make_links_absolute('http://www.mobygames.com')
# GameTitle
title = strip_accents(page('#gameTitle a').text()).strip()
gamedet.append(title)
# Grab core info
pagediv = page('.rightPanel #coreGameRelease div')
baseinfo = {}
for y in range(0,len(pagediv),2):
# left pane headings
category = strip_accents(pagediv.eq(y).text()).strip()
num1 = len(pagediv.eq(y+1)('a'))
baseinfo[category]=[]
baseinfo[str(category)+"_link"]=[]
for y1 in range(num1):
item = strip_accents(pagediv.eq(y+1)('a').eq(y1).text()).strip()
baseinfo[category].append(item)
link = pagediv.eq(y+1)('a').eq(y1).attr('href')
baseinfo[str(category)+"_link"].append(link)
gamedet.append(baseinfo)
gamedet.append(url)
mbtechplatind.append(gamedet)
######
#scrape moby platform credits page
######
def scrapepage3():
"""scrape moby platform credits page"""
writelog("starting platform credit page scrape")
start = time()
# count = 0
for x in credplatform:
url = "http://www.mobygames.com"+str(x)
url_hash = hashlib.sha1(url).hexdigest()
try:
f=open("cache/%s.txt" % url_hash, 'r')
# x=f.read()
# y = pq(x)
# print (str(count)+" | "+x+"/credits")
# count += 1
except IOError:
print ("scraping new html of "+url)
resp = urllib2.urlopen(url).read()
f = open("cache/%s.txt" % url_hash, 'w')
f.write(resp)
print ("done "+url)
except:
end = time()
elapse = str(td(seconds = end - start))
writelog("Error, platform credit scrape process stopped after: "+ elapse)
print "Error Time elapsed: " + elapse
raise
# count += 1
end = time()
elapse = str(td(seconds = end - start))
writelog("Completed platform credit scrape in " + elapse)
print "Time elapsed " + elapse
######
# Credit check sub
######
def credsubcheck(list):
global suberr
global suberr2
global subweird
global subcredinplace
global subcredplatform
global subcredredirect
suberr = []
suberr2 = []
subweird = []
subcredinplace = []
subcredplatform = []
subcredredirect = []
total = len(list)
print ("total: " + str(total))
creditcount = 0
creditinplacecount = 0
creditplatformcount = 0
nocreditcount = 0
other = 0
for x in list:
url = "http://www.mobygames.com" + str(x)
#print ("checking "+ url)
url_hash = hashlib.sha1(url).hexdigest()
try:
f = open("cache/%s.txt" % url_hash, 'r')
y = pq(f.read())
f.close()
z = y(".rightPanelMain p").text() # Check for main content
except:
print url
pass
try:
if "The following" in z: # Check for platform list
cd = y(".rightPanelMain ul li a")
for each in cd:
cred = each.attrib["href"]
subcredplatform.append(cred)
creditplatformcount += 1
subcredredirect.append(url)
creditcount += 1
elif "There are no credits" in z: # Check for no-credits
nocreditcount += 1
else:
try:
z1 = y(".rightPanelMain table").attr("summary") # Check for in place credits
if "List of Credits" in z1:
subcredinplace.append(url)
creditinplacecount += 1
else:
subweird.append(url)
other += 1
except:
suberr2.append(url)
except:
suberr.append(url)
#print ("done "+ url)
print ("Credits: "+ str(creditcount))
print ("Credits in platform: "+ str(creditplatformcount))
print ("Credits in place " + str(creditinplacecount))
print ("No Credits: "+ str(nocreditcount))
print ("Others :" + str(other))
print ("Errors " + str(len(suberr)))
print ("Error2s " + str(len(suberr2)))
######
#scrape mobyrank page
######
def scrapepage4():
"""scrape mobyrank page"""
writelog("starting moby rank page scrape")
start = time()
# count = 0
for x in scrap:
url = "http://www.mobygames.com"+str(x)+"/mobyrank"
url_hash = hashlib.sha1(url).hexdigest()
try:
f=open("cache/%s.txt" % url_hash, 'r')
# x=f.read()
# y = pq(x)
# print (str(count)+" | "+x+"/credits")
# count += 1
f.close()
except IOError:
print ("scraping new html of "+url)
resp = urllib2.urlopen(url).read()
f = open("cache/%s.txt" % url_hash, 'w')
f.write(resp)
print ("done "+url)
# count += 1
except:
end = time()
elapse = str(td(seconds = end - start))
writelog("Error, process stopped after: "+ elapse)
print "Error Time elapsed: " + elapse
raise
end = time()
elapse = str(td(seconds = end - start))
writelog("Completed mobyrank page scrape in " + elapse)
print "Time elapsed " + elapse
######
# Check for credits availability
######
def creditcheck():
global err
global err2
global weird
global credinplace
global credplatform
global crednocred
err = []
err2 = []
weird = []
credinplace = []
credplatform = []
crednocred = []
total = len(scrap)
print ("total: " + str(total))
creditcount = 0
creditinplacecount = 0
creditplatformcount = 0
nocreditcount = 0
other = 0
for x in scrap:
url = "http://www.mobygames.com"+str(x)+"/credits"
#print ("checking "+ url)
url_hash = hashlib.sha1(url).hexdigest()
f = open("cache/%s.txt" % url_hash, 'r')
y = pq(f.read())
z = y(".rightPanelMain p").text() # Check for main content
try:
if "The following" in z: # Check for platform list
cd = y(".rightPanelMain ul li a")
for each in cd:
cred = each.attrib["href"]
credplatform.append(cred)
creditplatformcount += 1
creditcount += 1
elif "There are no credits" in z: # Check for no-credits
nocreditcount += 1
crednocred.append(url)
else:
try:
z1 = y(".rightPanelMain table").attr("summary") # Check for in place credits
if "List of Credits" in z1:
credinplace.append(url)
creditinplacecount += 1
else:
weird.append(url)
other += 1
except:
err2.append(url)
except:
err.append(url)
#print ("done "+ url)
f.close()
print ("Credits: "+ str(creditcount))
print ("Credits in platform: "+ str(creditplatformcount))
print ("Credits in place " + str(creditinplacecount))
print ("No Credits: "+ str(nocreditcount))
print ("Others :" + str(other))
print ("Errors " + str(len(err)))
print ("Error2s " + str(len(err2)))
######
# Scrape moby credits sub page ordering by developer
######
def scrapepage5(list):
"""scrape moby credits sub page ordering by developer"""
writelog("starting mob game credit sub page scrape")
start = time()
for x in list:
url = x
url_hash = hashlib.sha1(url).hexdigest()
try:
f=open("cache/%s.txt" % url_hash, 'r')
x=f.read()
print ("extracting "+url)
y = pq(x)
gametitle = y("#gameTitle a").text().encode("utf-8")
gameplatform = y("#gamePlatform").text().encode("utf-8")
core = y("#coreGameRelease a") # Basic Information block
gamepublisher = core[0].text_content().encode("utf-8")
gamedeveloper = core[1].text_content().encode("utf-8")
gamerelease = core[2].text_content().encode("utf-8")
core2 = y("#coreGameGenre a")
core2num = len(core2) # Begin dealing with variable info block
gamemisc = []
for x in range (0,core2num):
if x == 0:
gamegenre = core2[0].text_content().encode("utf-8")
elif x == 1:
gameperspective = core2[1].text_content().encode("utf-8")
else:
misc = core2[x].text_content().encode("utf-8")
gamemisc.append(misc)
if len(gamemisc) == 0:
gamemisc = "Nil"
mobyrank = y(".scoreBoxBig").text()
mobyscore = y(".scoreBoxMed").text()
main = y(".rightPanelMain tr") #Get the main info
num = len(main) #get the number of table rows
for x in range(0,num): #begin ripping the table contents apart
stuff = main[x].attrib
if not stuff: # check for header row
affiliation = main[x].text_content()
else:
position = main[x][0].text_content().encode("utf-8")
memnum = len(main[x][1])
if memnum == 0:
#print ("memnum = "+str(memnum))
member = main[x][1].text_content().encode("utf-8")
c.writerow([member]+[position]+[affiliation]+[gametitle]+[gameplatform]+[gamepublisher]+[gamedeveloper]+[gamerelease]+[gamegenre]+[gameperspective]+[gamemisc]+[mobyrank]+[mobyscore])
else:
for z in range(0,memnum):
#print("else memnum = "+str(z))
member = main[x][1][z].text_content().encode("utf-8")
c.writerow([member]+[position]+[affilation]+[gametitle]+[gameplatform]+[gamepublisher]+[gamedeveloper]+[gamerelease]+[mobyrank]+[mobyscore]+[gamegenre]+[gameperspective]+[gamemisc])
print ("done "+url)
#break
except IOError:
print ("scraping new html of "+str(x))
resp = urllib2.urlopen(url).read()
f = open("cache/%s.txt" % url_hash, 'w')
f.write(resp)
print ("done "+str(x))
except:
end = time()
elapse = str(td(seconds = end - start))
writelog("Error, process stopped after: "+ elapse)
print "Error Time elapsed: " + elapse
raise
end = time()
elapse = str(td(seconds = end - start))
writelog("Completed moby credit sub page scrape in " + elapse)
print "Time elapsed " + elapse
#break
#thinking about it....
####
# to dig studio/contribution affiliation
####
'''for i in range(0,num):
stuff = x[i].attrib
if not stuff:
print (x[i].text_content())
affiliation = x[i].text_content()
else:
print (x[i][0].text_content()+" "+x[i][1].text_content()+" "+affiliation)'''
######
# scrape moby release info page
######
def scrapepage6():
"""scrape moby release info page"""
writelog("starting moby release info page scrape")
start = time()
for x in scrap:
url = "http://www.mobygames.com"+str(x)+"/release-info"
url_hash = hashlib.sha1(url).hexdigest()
try:
f=open("cache/%s.txt" % url_hash, 'r')
#x=f.read()
#y = pq(x)
except IOError:
print ("scraping new html of "+url)
resp = urllib2.urlopen(url).read()
f = open("cache/%s.txt" % url_hash, 'w')
f.write(resp)
print ("done "+url+" info")
except:
end = time()
elapse = str(td(seconds = end - start))
writelog("Error, process stopped after: "+ elapse)
print "Error Time elapsed: " + elapse
raise
end = time()
elapse = str(td(seconds = end - start))
writelog("Completed release info page scrape in " + elapse)
print "Time elapsed " + elapse
######
# scrape moby techinfo page
######
def scrapepage7():
"""scrape moby tech info page"""
writelog("starting moby tech info page scrape")
start = time()
for x in scrap:
url = "http://www.mobygames.com"+str(x)+"/techinfo"
url_hash = hashlib.sha1(url).hexdigest()
try:
f=open("cache/%s.txt" % url_hash, 'r')
#x=f.read()
#y = pq(x)
except IOError:
print ("scraping new html of "+url)
while True: # Unlimited tries to pull data
try:
resp = urllib2.urlopen(url).read()
f = open("cache/%s.txt" % url_hash, 'w')
f.write(resp)
break
except urllib2.URLError, (err):
print ("URL error(%s)" % (err))
writelog(str(err) + "| Error, retrying...")
print ("Retrying...")
pass
except:
pass
print ("done "+url)
except:
end = time()
elapse = str(td(seconds = end - start))
writelog("Error, process stopped after: "+ elapse)
print "Error Time elapsed: " + elapse
raise
end = time()
elapse = str(td(seconds = end - start))
writelog("Completed tech info page scrape in " + elapse)
print "Time elapsed " + elapse
######
# scrape business model
######
def bizmodelcheck():
"""check tech info page for business model"""
writelog("starting capturing of business model data test")
start = time()
global bizmodel
bizmodel = []
for x in scrap:
url = "http://www.mobygames.com"+str(x)+"/techinfo"
url_hash = hashlib.sha1(url).hexdigest()
try:
f=open("cache/%s.txt" % url_hash, 'r')
except:
raise
x=f.read()
y=pq(x)
main = y(".rightPanelMain table").text()
# check for business model in table
if "Business Model" in strip_accents(main):
bizmodel.append(url)
print ("Completed process")
end = time()
elapse = str(td(seconds = end - start))
writelog("Completed checking of tech info business model in " + elapse)
print "Time elapsed " + elapse
######
# scrape business model detail
######
def bizmoddetgrab():
"""grab business model"""
writelog("starting grab of business model detail test")
start = time()
print "Running business model detail grab"
global bizdet
bizdet = []
for xurl in bizmodel:
url = xurl
url_hash = hashlib.sha1(url).hexdigest()
try:
f=open("cache/%s.txt" % url_hash, 'r')
except:
raise
check = 0 #debug check
x=f.read()
y=pq(x)
table = y(".rightPanelMain table")
num = len(table)*2
for x in range(2,num+1,2): # Check table details
str2 = ".rightPanelMain > table.techInfo:nth-child({0}) > tr > td:nth-child(1)".format(x)
column1 = strip_accents(y(str2).text())
if "Business Model" in column1:
#grab platform model
str1 = ".rightPanelMain > table.techInfo:nth-child({0}) thead".format(x)
platform = strip_accents(y(str1).text())
#print platform
#grab game name
gamename = strip_accents(y("#gameTitle a").text()) # get gamename
#print gamename
# getting release date
listing = [strip_accents(z.text_content()) for z in y("#coreGameRelease > div")]
# getting indexes and corresponding items
try:
indexrel = listing.index("Released")
releasedate = listing[indexrel+1]
except:
releasedate = 'nil'
#print releasedate
# get column1 rows in a table
str3 = ".rightPanelMain > table.techInfo:nth-child({0}) > tr > td:nth-child(1)".format(x)
rows = y(str3)
rownum = len(rows)
rowlisting = []
for row in rows:
rowlisting.append(strip_accents(row.text_content()))
targetrownum = rowlisting.index("Business Model")
# get target row in column 2
str4 = ".rightPanelMain > table.techInfo:nth-child({0}) > tr > td:nth-child(2)".format(x)
column2rows = y(str4)
model = strip_accents(column2rows[targetrownum].text_content())
# print model
# print url
bizdet.append([gamename,platform,releasedate,model,url])
check += 1
# print "Found"
if check == 0:
print url + " nothing?"
print ("Completed process")
end = time()
elapse = str(td(seconds = end - start))
writelog("Completed grab of business model detail test in " + elapse)
print "Time elapsed " + elapse
#####
# mobyrank individual platform scrap
#####
def scrapepage8(list):
"""scrape mobyrank individual platform page"""
print ("starting mobyrank individual platform scrape")
writelog("starting mobyrank individual platform scrape test")
start = time()
for x in list:
url = "http://www.mobygames.com"+str(x)
url_hash = hashlib.sha1(url).hexdigest()
try:
f=open("cache/%s.txt" % url_hash, 'r')
#x=f.read()
#y = pq(x)
except IOError:
print ("scraping new html of "+url)
while True: # Unlimited tries to pull data
try:
resp = urllib2.urlopen(url).read()
f = open("cache/%s.txt" % url_hash, 'w')
f.write(resp)
break
except urllib2.URLError, (err):
print ("URL error(%s)" % (err))
writelog(str(err) + "| Error, retrying...")
print ("Retrying...")
pass
except KeyboardInterrupt:
raise
print ("done "+url)
except:
end = time()
elapse = str(td(seconds = end - start))
writelog("Error, process stopped after: "+ elapse)
print "Error Time elapsed: " + elapse
raise
end = time()
elapse = str(td(seconds = end - start))
writelog("Completed mobyrank individual platform scrape test in " + elapse)
print "Time elapsed " + elapse
########
# Grab parts of the moby list
########
def scrapelist():
# linecount = 0
for x in num:
url = "http://www.mobygames.com/browse/games/offset,"+str(x)+"/so,0a/list-games/"
url_hash = hashlib.sha1(url).hexdigest()
try:
f=open("cache/%s.txt" % url_hash, 'r')
x=f.read()
y = pq(x)
for stuff in y("#mof_object_list tbody td"):
grab1.append(stuff.text_content())
except IOError:
print "scraping new html of "+str(x)
resp = urllib2.urlopen(url).read()
f = open("cache/%s.txt" % url_hash, 'w')
f.write(resp)
print "done "+str(x)
############## Grab to types #####################
def initgamelist():
global gamename
global gameyear
global gampublisher
global gamegenre
global gameplatform
gamename = []
gameyear = []
gamepublisher = []
gamegenre = []
gameplatform = []
def grabtype():
"""grab field types from gamebrowser list"""
for x in num:
url = "http://www.mobygames.com/browse/games/offset,"+str(x)+"/so,0a/list-games/"
url_hash = hashlib.sha1(url).hexdigest()
try:
f=open("cache/%s.txt" % url_hash, 'r')
x=f.read()
y = pq(x)
for stuff in y("#mof_object_list tbody td"):
grab1.append(stuff.text_content())
except IOError:
print "end"
objcnt = 0
for stuff in grab1:
if int(objcnt)%5 == 0: # gamename
gamename.append(stuff)
elif int(objcnt)%5 == 1: # gameyear
gameyear.append(stuff)
elif int(objcnt)%5 == 2: # gamepublisher
gamepublisher.append(stuff)
elif int(objcnt)%5 == 3: # gamegenre
gamegenre.append(stuff)
elif int(objcnt)%5 == 4: # gameplatform
gameplatform.append(stuff)
objcnt += 1
###########
# grab individual game details: Publisher, Developer, Release Date, Platform
###########
def gamedetgrab(list):
"""grab individual game details: Publisher, Developer, Release Date, Platform check"""
global deterr
global det8
global det6
global det6nopub
global det6nodev
global det6norel
global det6noplat
global det4
deterr = []
det8 = []
det6 =[]
det6nopub = []
det6nodev = []
det6norel = []
det6noplat = []
det4 = []
det4nopub = []
det4nodev = []
det4norel = []
det4noplat = []
print ("grabing game details from list")
writelog("starting game detail grab test")
start = time()
print ("No. of items in list: " + str(len(list)))
for x in list:
url = "http://www.mobygames.com"+str(x)
url_hash = hashlib.sha1(url).hexdigest()
try:
f = open("cache/%s.txt" % url_hash, 'r')
x = f.read()
y = pq(x)
detpanel = y('.rightPanel #coreGameRelease div')
if len(detpanel) is 8:
det8.append(url)
elif len(detpanel) is 6:
det6.append(url)
det6list = [strip_accents(x.text_content()) for x in detpanel]
if "Published by" not in det6list:
det6nopub.append(url)
elif "Developed by" not in det6list:
det6nodev.append(url)
elif "Released" not in det6list:
det6norel.append(url)
elif "Platforms" not in det6list:
if "Platform" not in det6list:
det6noplat.append(url)
elif len(detpanel) is 4:
det4.append(url)
det4list = [strip_accents(x.text_content()) for x in detpanel]
if "Published by" not in det4list:
det4nopub.append(url)
elif "Developed by" not in det4list:
det4nodev.append(url)
elif "Released" not in det4list:
det4norel.append(url)
elif "Platforms" not in det4list:
if "Platform" not in det4list:
det4noplat.append(url)
else:
print (url)
deterr.append(url)
except:
print (x)
raise
print "8 fields: " + str(len(det8))
print "6 fields: " + str(len(det6))
print "---- No Publisher: " + str(len(det6nopub))
print "---- No Developer: " + str(len(det6nodev))
print "---- No Release date: " + str(len(det6norel))
print "---- No Platforms: " + str(len(det6noplat))
print "4 fields: " + str(len(det4))
print "---- No Publisher: " + str(len(det4nopub))
print "---- No Developer: " + str(len(det4nodev))
print "---- No Release date: " + str(len(det4norel))
print "---- No Platforms: " + str(len(det4noplat))
print "Errors: " + str(len(deterr))
end = time()
elapse = str(td(seconds = end - start))
writelog("Completed game detail grab test in " + elapse)
print "Time elapsed " + elapse
def gamedetgrab2(list):
"""grab individual game details: Publisher, Developer, Release Date, Platform"""
print ("grabing game details from list...")
writelog("starting game detail grab test 2")
start = time()
global gamenameandplatform
gamenameandplatform = []
for x in list:
url = "http://www.mobygames.com"+str(x)
url_hash = hashlib.sha1(url).hexdigest()
try:
f = open("cache/%s.txt" % url_hash, 'r')
x = f.read()
y = pq(x)
gamename = strip_accents(y('#gameTitle').text())
detpanel = y('.rightPanel #coreGameRelease div')
detlist = [strip_accents(x.text_content()) for x in detpanel]
gamerelease = strip_accents(detlist[-3])
gamereleaseyear = yeargrab(gamerelease)
platformlist = detlist[-1].split(',')
for x in platformlist:
gameplatform = x.strip()
gamenameandplatform.append([gamename,gameplatform,gamerelease])
except:
raise
print "listing: " + str(len(gamenameandplatform))
print ('Done grab test 2')
end = time()
elapse = str(td(seconds = end - start))
writelog("Completed game detail grab test 2 in " + elapse)
print "Time elapsed " + elapse
def gamedetgrab3(list):
"""grab individual game details: Publisher, Developer, Release Date, Platform + genre and other craps"""
print ("grabing game genre from list...")
writelog("starting game genre grab test")
start = time()
global gamegenres
global gamegenrelisting
gamegenres = []
gamegenrelisting = []
global genrecollation
genrecollation = []
#count = 0
for x in list:
#count += 1
url = "http://www.mobygames.com"+str(x)
url_hash = hashlib.sha1(url).hexdigest()
try:
f = open("cache/%s.txt" % url_hash, 'r')
x = f.read()
y = pq(x)
f.close()
except:
raise
gamename = strip_accents(y('#gameTitle').text())
detpanel = y('.rightPanel #coreGameRelease div')
detlist = [strip_accents(x.text_content()) for x in detpanel]
gamerelease = strip_accents(detlist[-3])
gamereleaseyear = yeargrab(gamerelease)
gamegenre = []
# General Genre Classification
c1 = 'Nil' # Action
c2 = 'Nil' # Adventure
c3 = 'Nil' # Educational
c4 = 'Nil' # Racing / Driving
c5 = 'Nil' # Role-Playing (RPG)
c6 = 'Nil' # Simulation
c7 = 'Nil' # Sports
c8 = 'Nil' # Strategy
genrelist = (y("#coreGameGenre div div"))
if len(genrelist): # Check for genre existence
listing = []
for x in genrelist:
listing.append(strip_accents(x.text_content()))
gamegenrelisting.append(strip_accents(x.text_content()))
try:
genrepos = listing.index('Genre')
genreclasses = genrelist[genrepos+1]
for x in genreclasses:
gamegenre.append(strip_accents(x.text_content()))
gamegenre.sort()