-
Notifications
You must be signed in to change notification settings - Fork 0
/
oneStep.py
4205 lines (3513 loc) · 178 KB
/
oneStep.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
import logging
import io
import ftfy
import copy
from collections import Counter
from math import floor
from decimal import *
import urllib.request as urllib
from urllib.request import urlopen
import socket
import statistics
import functools
import math
import string
from functools import cmp_to_key
from bs4 import BeautifulSoup
import json
import time
import argparse
import ftplib
import datetime
#for timezone
import pytz
import sys
import os
#wrap entire script in try/except to catch any errors
try:
#READ COMMAND LING ARGS
parser = argparse.ArgumentParser(description='silent checking script')
parser.add_argument('link', action='store', type=str, help='FTP Link')
parser.add_argument('user', action='store', type=str, help='FTP Username')
parser.add_argument('passo', action='store', type=str, help='FTP Password')
parser.add_argument('-textarg', action='store', type=str, help='Input time string if not using default.')
# you would call -textarg with a string like "1671490801" like so:
# python3 oneStep.py link user pass -textarg "1671490801"
# add optional argument called -nuclear with default value False
parser.add_argument('-nuclear', action='store_true', default=False, help='Re-fetch ALL files from fillmore.homelinux. Will take a long time.')
# add optional argument called -neuter with default value False
parser.add_argument('-neuter', action='store_true', default=False, help='Dump in temp but not to curr. Useful for testing.')
# add optional argument called -local with default value False
parser.add_argument('-local', action='store_true', default=False, help='Use relative directories. Default false, as default target is defined VPS environment');
parse_results = parser.parse_args()
#create var neuter
textarg = parse_results.textarg
nuclear = parse_results.nuclear
neuter = parse_results.neuter
localbool = parse_results.local
start_time = int(time.time())
GMTTime = datetime.datetime.now()
eastern = pytz.timezone('US/Eastern')
ESTTime = GMTTime.astimezone(eastern)
#logging.basicConfig(encoding='utf-8', format='%(asctime)s %(levelname)-8s %(message)s', level=logging.INFO, datefmt='%Y-%m-%d %H:%M:%S')
#logging.basicConfig(encoding='utf-8', level=logging.DEBUG)
# COMMON BETWEEN BOTH
root_logger= logging.getLogger()
root_logger.setLevel(logging.DEBUG) # or whatever
if (localbool):
# make ./logs if not there
if not os.path.exists('logs'):
os.makedirs('logs')
#FOR RUNNING ON LOCAL MAC
handler = logging.FileHandler(filename="logs/"+str(start_time)+'.log', mode='w', encoding='utf-8')
handler2 = handler
handler.setFormatter(logging.Formatter('%(name)s %(message)s')) # or whatever
root_logger.addHandler(logging.StreamHandler(sys.stdout))
else:
#FOR RUNNING ON VPS
handler = logging.FileHandler('/root/sxctrack/test.log', 'w', 'utf-8') # or whatever
handler2 = logging.FileHandler('/root/sxctrack/logs/'+GMTTime.strftime("GMT_%Y-%m-%d_%H:%M:%S_oneStep.log"), "w", "utf-8")
handler.setFormatter(logging.Formatter('%(name)s %(message)s')) # or whatever
# COMMON BETWEEN BOTH
root_logger.addHandler(handler)
root_logger.addHandler(handler2)
log_stream = io.StringIO()
log_handler = logging.StreamHandler(log_stream)
root_logger.addHandler(log_handler)
#BEGIN
logging.info("starting time: " + str(start_time))
logging.info("GMT Time: " + GMTTime.strftime("%Y-%m-%d, %H:%M:%S"))
logging.info("EST Time: " + ESTTime.strftime("%Y-%m-%d, %H:%M:%S"))
logging.info("Starting update check...")
#LOG INTO FTP
ftpHost = parse_results.link
ftpUser = parse_results.user
ftpPassword = parse_results.passo
logging.info("logging into FTP...")
# logging.info("host: "+str(ftpHost)+", user: "+str(ftpUser)+", pass: "+str(ftpPassword)+".")
# SHOULD NOT LOG LOGIN INFO!
# ftpObject = ftplib.FTP_TLS(ftpHost)
ftpObject = ftplib.FTP(ftpHost)
# ftpObject.set_pasv(False)
def ftpLogin():
logging.info("attempting ftp login")
# should I make sure that we're not already logged in / kill any existing FTP work?
for i in range(3):
try:
ftpObject.login(user=ftpUser, passwd=ftpPassword)
break
except:
logging.info("failed to login, trying again...")
time.sleep(1)
if i == 2:
logging.info("failed to login, exiting...")
exit()
continue
logging.info("login successful")
# define failed FTP login class so it looks nice
class FTPLoginFailed(Exception):
pass
def ftpLoginThrow():
logging.info("attempting ftp login")
# should I make sure that we're not already logged in / kill any existing FTP work?
for i in range(3):
try:
ftpObject.login(user=ftpUser, passwd=ftpPassword)
break
except Exception as e:
logging.info("failed to login, trying again...")
logging.info("specific error: "+str(e)+".")
time.sleep(1)
if i == 2:
logging.info("failed to login, exiting...")
raise FTPLoginFailed("couldn't log in")
logging.info("login successful")
def ftpLogout():
logging.info("ftp logging out...")
ftpObject.quit()
logging.info("ftp logged out")
def ftpLogoutLogin():
logging.info("ftp logging out...")
ftpObject.quit()
logging.info("ftp logged out")
ftpObject = ftplib.FTP(ftpHost)
ftpLoginThrow()
def navigateToRoot():
for i in range(6):
try:
ftpObject.cwd("/")
break
except Exception as e:
logging.info("could not navigate: "+str(e))
logging.info("trying again... (attempt "+str(i+1)+" of 6)")
time.sleep(1)
if i == 2:
logging.info("failed to navigate to root, trying to log out and log in to recover...")
ftpLogoutLogin
# if ftpLogin fails, the script fails permanently
# else, try this until i = 5
if i == 5:
logging.info("failed to navigate to root even after re-logging in, exiting...")
exit()
continue
# supposedly works
ftpLogin()
#FTP FUNCTIONS
#navigate to directory ALWAYS FROM ROOT and create it if it does not exist
def chdir(dir):
logging.info("chdir: "+str(dir))
#navigate to root
#attempt to navigate to root a maximum of 3 times if it fails
# if this fails, try to log in again?
navigateToRoot()
#split by /
dirSplit = dir.split("/")
#remove empty
dirSplit = [x for x in dirSplit if x]
logging.info("chdir: "+str(dirSplit))
for dirStr in dirSplit:
if directory_exists(dirStr):
#attempt to navigate to directory a maximum of 3 times if it fails
for i in range(3):
try:
ftpObject.cwd(dirStr)
break
except:
logging.info("failed to navigate to directory "+str(dirStr)+", trying again... (attempt "+str(i)+" of 3)")
time.sleep(1)
if i == 2:
logging.info("failed to navigate to directory, exiting...")
exit()
continue
else:
logging.info("creating new dir '"+dirStr+"' at "+str(ftpObject.pwd()))
#attempt to make directory a maximum of 3 times if it fails
for i in range(3):
try:
ftpObject.mkd(dirStr)
break
except:
logging.info("failed to make directory "+str(dirStr)+", trying again... (attempt "+str(i)+" of 3)")
time.sleep(1)
if i == 2:
logging.info("failed to make directory, exiting...")
exit()
continue
#attempt to navigate to directory a maximum of 3 times if it fails
for i in range(3):
try:
ftpObject.cwd(dirStr)
break
except:
logging.info("failed to navigate to directory "+str(dirStr)+", trying again... (attempt "+str(i)+" of 3)")
time.sleep(1)
if i == 2:
logging.info("failed to navigate to directory, exiting...")
exit()
continue
#helper function
def directory_exists(dir):
filelist = []
#attempt to get file list a maximum of 3 times if it fails
for i in range(3):
try:
ftpObject.retrlines('LIST', filelist.append)
break
except:
logging.info("failed to get file list, trying again... (attempt "+str(i)+" of 3)")
time.sleep(1)
if i == 2:
logging.info("failed to get file list, exiting...")
exit()
continue
for f in filelist:
if f.split()[-1] == dir and f.upper().startswith('D'):
return True
return False
#store ftp file to variable
def getFileFTP(fileNameStr):
pythonData = io.BytesIO()
#attempt to get file a maximum of 3 times if it fails
for i in range(3):
try:
ftpObject.retrbinary('RETR ' + fileNameStr, pythonData.write)
break
except:
logging.info("failed to get file, trying again... (attempt "+str(i)+" of 3)")
time.sleep(1)
if i == 2:
logging.info("failed to get file, exiting...")
exit()
continue
return pythonData.getvalue()
#delete all files within a folder
def deleteFilesInDir(dir):
logging.info("deleting all files in '"+str(dir)+"'")
# navigate to root
#attempt to navigate to root a maximum of 3 times if it fails
navigateToRoot()
# split by /
dirSplit = dir.split("/")
# remove empty
dirSplit = [x for x in dirSplit if x]
#print(dirSplit)
for dirStr in dirSplit:
if directory_exists(dirStr):
# attempt to navigate to directory a maximum of 3 times if it fails
for i in range(3):
try:
ftpObject.cwd(dirStr)
break
except:
logging.info("failed to navigate to directory " + str(dirStr) + ", trying again... (attempt " + str(i) + " of 3)")
time.sleep(1)
if i == 2:
logging.info("failed to navigate to directory, exiting...")
exit()
continue
else:
logging.info("Did not delete items in " + dirStr + ", directory does not exist")
return
#find all items in directory...
itemList = ftpObject.nlst()
logging.info("files: "+str(itemList))
for i in enumerate(itemList):
logging.info("testing item '"+str(i[1])+"'")
if directory_exists(i[1]):
logging.info("this is a directory...")
deleteFilesInDir(dir + i[1] + "/")
chdir(dir)
#attempt to remove directory a maximum of 3 times if it fails
for j in range(3):
try:
ftpObject.rmd(dir + i[1])
break
except:
logging.info("failed to remove directory, trying again... (attempt "+str(j)+" of 3)")
time.sleep(1)
if j == 2:
logging.info("failed to remove directory, exiting...")
exit()
continue
else:
logging.info("deleting '" + dir + str(i[1]) + "'")
#attempt to delete file a maximum of 3 times if it fails
for j in range(3):
try:
ftpObject.delete(dir + i[1])
break
except:
logging.info("failed to delete file, trying again... (attempt "+str(j)+" of 3)")
time.sleep(1)
if j == 2:
logging.info("failed to delete file, exiting...")
exit()
continue
#move one folder's contents to another folder
def moveContents(dir, newDir):
logging.info("moving files from '"+dir+"' to '"+newDir+"'")
# navigate to root
#attempt to navigate to root a maximum of 3 times if it fails
navigateToRoot()
# split by /
dirSplit = dir.split("/")
# remove empty
dirSplit = [x for x in dirSplit if x]
#print(dirSplit)
for dirStr in dirSplit:
if directory_exists(dirStr):
# attempt to navigate to directory a maximum of 3 times if it fails
for i in range(3):
try:
ftpObject.cwd(dirStr)
break
except:
logging.info("failed to navigate to directory " + str(dirStr) + ", trying again... (attempt " + str(i) + " of 3)")
time.sleep(1)
if i == 2:
logging.info("failed to navigate to directory, exiting...")
exit()
continue
else:
logging.info("Did not move contents " + dirStr + ", directory does not exist")
return
#find all items in directory...
itemList = ftpObject.nlst()
for i in enumerate(itemList):
#print(i)
#rename file
currDir = dir
fileName = i[1]
print("moving '"+currDir+""+str(fileName)+"' to "+str(newDir)+fileName)
#attempt to rename file a maximum of 3 times if it fails
for i in range(3):
try:
ftpObject.rename(currDir+""+fileName, newDir+""+fileName)
break
except:
logging.info("failed to rename file, trying again... (attempt "+str(i)+" of 3)")
time.sleep(1)
if i == 2:
logging.info("failed to rename file, exiting...")
exit()
continue
#print(str(itemList))
def copyFile(fullFileName, targetDir):
# navigate to root
#attempt to navigate to root a maximum of 3 times if it fails
navigateToRoot()
# split by /
dirSplit = fullFileName.split("/")
fileName = dirSplit[-1]
dirSplit = dirSplit[:-1]
dirSplit = dirSplit[1:]
#logging.info("dirSplit: "+str(dirSplit))
# remove empty
dirSplit = [x for x in dirSplit if x]
# print(dirSplit)
for dirStr in dirSplit:
if directory_exists(dirStr):
# attempt to navigate to directory a maximum of 3 times if it fails
for i in range(3):
try:
ftpObject.cwd(dirStr)
break
except:
logging.info("failed to navigate to directory " + str(dirStr) + ", trying again... (attempt " + str(i) + " of 3)")
time.sleep(1)
if i == 2:
logging.info("failed to navigate to directory, exiting...")
exit()
continue
else:
logging.info("Did not move file " + str(fullFileName) + ", directory does not exist")
return
#logging.info("fileName: "+str(fileName))
logging.info("FILE: copying file '"+fullFileName+"' ("+fileName+") to '" + targetDir + "'")
fileTempBytes = io.BytesIO(getFileFTP(fileName))
chdir(targetDir)
#attempt to store file a maximum of 3 times if it fails
for i in range(3):
try:
ftpObject.storbinary('STOR '+fileName, fileTempBytes)
break
except:
logging.info("failed to store file, trying again... (attempt "+str(i)+" of 3)")
time.sleep(1)
if i == 2:
logging.info("failed to store file, exiting...")
exit()
continue
#go back to prev. directory
chdir("/"+joinArr(dirSplit, "/")+"/")
logging.info("FILE: success")
def copyContents(dir, newDir):
# navigate to root
# attempt to navigate to root a maximum of 3 times if it fails
navigateToRoot()
# split by /
dirSplit = dir.split("/")
# remove empty
dirSplit = [x for x in dirSplit if x]
# print(dirSplit)
for dirStr in dirSplit:
if directory_exists(dirStr):
# attempt to navigate to directory a maximum of 3 times if it fails
for i in range(3):
try:
ftpObject.cwd(dirStr)
break
except:
logging.info("failed to navigate to directory " + str(dirStr) + ", trying again... (attempt " + str(i) + " of 3)")
time.sleep(1)
if i == 2:
logging.info("failed to navigate to directory, exiting...")
exit()
continue
else:
logging.info("Did not move contents of " + str(dir) + ", directory does not exist")
return
# find all items in directory...
# attempt to get list of files a maximum of 3 times if it fails
for i in range(3):
try:
itemList = ftpObject.nlst()
break
except:
logging.info("failed to get list of files, trying again... (attempt " + str(i) + " of 3)")
time.sleep(1)
if i == 2:
logging.info("failed to get list of files, exiting...")
exit()
continue
logging.info("DIR: copying files from '"+dir+"' to '" + newDir + "' - "+str(itemList))
#logging.info("thing list: "+str(itemList))
for i in enumerate(itemList):
chdir(dir)
logging.info("testing item '" + str(i[1]) + "'")
#check if this is yet another directory...
if directory_exists(i[1]):
#logging.info("item '"+i[1]+"' is a dir...")
chdir(newDir+i[1]+"/")
copyContents(dir+i[1]+"/", newDir+i[1]+"/")
else:
# print(i)
#logging.info("copying " + str(i[1]) + " to " + str(newDir))
# rename file
currDir = dir
fileName = i[1]
copyFile(currDir+fileName, newDir)
logging.info("DIR: success ("+dir+" -> "+newDir+")")
def joinArr(list, separator=", "):
return separator.join(list)
#REMOTE PAGE FUNCTIONS
def fetch_remote_page(url):
page = "err"
# attempt to open page a maximum of 3 times if it fails
for i in range(3):
try:
page = urlopen(url, timeout=30)
if i > 0:
logging.info("success on attempt " + str(i+1))
break
except socket.timeout as n:
logging.error("Socket error on attempt " + str(i+1) + " of 3")
logging.error(n)
time.sleep(1)
page = "err"
continue
except urllib.URLError as n:
logging.error("Could not open page. Attempt " + str(i+1) + " of 3")
logging.error(n)
time.sleep(1)
page = "err"
continue
return page
#specifically for http://fillmore.homelinux.net/cgi-bin/Meets?year=*
def parse_remote_meet_page(page_data):
# read page_data
read_data = page_data.read()
# decode by utf-8
html = read_data.decode("utf-8")
# use beautifulsoup
soup = BeautifulSoup(html, "html.parser")
# THIS IS SPECIFIC TO THIS SPECIFIC FILLMORE.HOMELINUX.NET PAGE
# main table
meet_table = soup.find("form").table
# row array (recursive=False, just in case)
row_list = meet_table.find_all("tr", recursive=False)
# remove the title row (contains search bars and other stuff not useful)
row_list.pop(0)
# now, the fun part
remote_meets_array = []
for temp_meet in row_list:
meet_object = {
"date": temp_meet.find_all("td")[0].getText(),
"gender": temp_meet.find_all("td")[1].getText(),
"name": temp_meet.find_all("td")[2].getText(),
"season": temp_meet.find_all("td")[3].getText(),
"location": temp_meet.find_all("td")[4].getText(),
"id": temp_meet.a.get('href').split("=")[1]
}
remote_meets_array.append(meet_object)
# return array
return remote_meets_array
def get_ids(objList):
outputArr = []
for objTemp in objList:
outputArr.append(int(objTemp['id']))
return outputArr
def findFreshIDs(objList):
# for every item in objList:
# if date is within 2 weeks of today:
# if date is now or the future:
# add id to outputArr
# well, you see, anything past two weeks ago would also
# include meets that are in the future, so we don't need
# to check for that specifically
#define today
today = datetime.date.today()
#define two weeks ago
twoWeeksAgo = today - datetime.timedelta(days=14)
#define output array
outputArr = []
#loop through objList
for objTemp in objList:
#log date
# logging.info("date: "+objTemp['date'])
#get date
dateTemp = datetime.datetime.strptime(objTemp['date'], "%Y-%m-%d").date()
#compare date
if dateTemp > twoWeeksAgo:
#add id to outputArr
outputArr.append(int(objTemp['id']))
return outputArr
def find_new_ids(local_list, remote_list):
#logging.info("local list:"+str(local_list))
#logging.info("local list:"+str(len(local_list)))
#logging.info("first item test:"+str(local_list[0]))
# get array of IDs from local_list
#just_ids_local = [d['id'] for d in local_list]
just_ids_local = local_list
# get array of IDs from remote_list
#just_ids_remote = [d['id'] for d in remote_list]
just_ids_remote = remote_list
# find differences
# remote - local, assuming that there will be more meets from remote than local
s = set(just_ids_local)
diff_array = [x for x in just_ids_remote if x not in s]
# diff_array = list(set(just_ids_remote) - set(just_ids_local))
# return array
return diff_array
def fetch_basic_remote_data(meet_id):
#logging.info("all meet ids: "+str(all_meet_ids))
for obj in remote_basic_data:
if obj["id"] == str(meet_id):
return obj
print("no meet found")
return "no meet"
def read_meet_page(meet_id):
#setup basic obj
meet_object = fetch_basic_remote_data(meet_id)
# set url
meetBaseUrl = "http://fillmore.homelinux.net/cgi-bin/Meet?meet="
tempUrl = meetBaseUrl + str(meet_id)
tempPage = fetch_remote_page(tempUrl)
if tempPage == None:
logging.error("meet page failed to load")
meet_object['categories'] = "URLError"
return meet_object
# READY BEAUTIFULSOUP
# parse
tempHtml_bytes = tempPage.read()
# decode
tempHtml = tempHtml_bytes.decode("utf-8")
# soup
tempSoup = BeautifulSoup(tempHtml, "html.parser")
#ready local variables
trList = []
# h3 = meet annotation
meet_object["annotation"] = tempSoup.h3.getText()
# check if there's a footer
if len(tempSoup.find_all("div", recursive=False)) > 1:
#print("possible footer")
temp_footer = str(tempSoup.find_all("div", class_="main")[0])
temp_footer = temp_footer.split('<div class="main">')[1]
temp_footer = temp_footer.split('</div>')[0]
temp_footer = temp_footer.replace("\r", "")
temp_footer = temp_footer.replace("<br/>", "\r")
temp_footer = temp_footer.replace("\r \r", "\r\r")
meet_object["footer"] = temp_footer
else:
#print("no footer")
if 'footer' in meet_object:
meet_object.pop("footer")
# contains div
# recursive=False means that it won't find nested tables. perfect.
tableContainer = tempSoup.find_all("div")[1].find_all("table", recursive=False)
# throw away empty table elements
for y in range(len(tableContainer)):
# start from back because otherwise things get funky
zed = len(tableContainer) - 1 - y
if len(tableContainer[zed].find_all("tr")) == 0:
tableContainer.pop(zed)
#for the top-level tables on the page
for z in range(len(tableContainer)):
#current table row:
currentThing = tableContainer[z].find_all("tr", recursive=False)
# for each table row in a top-level table
for orange in range(len(currentThing)):
#add to trList array
trList.append(currentThing[orange])
#now, go through each table row (these contain either category data or a category title)
#set up variables
trTrList = []
tempTitle = None
for count in range(len(trList)):
#check if is title
if len(trList[count].find_all("th")) == 1:
# title
tempTitle = trList[count].find_all("th")[0].getText()
else:
# not title. If tempTitle is not None, set this table's title.
if tempTitle is not None:
#add category name to list along with table row data
trTrList.append({"name": tempTitle, "data": trList[count]})
#reset tempTitle
tempTitle = None
else:
#add uncategorized category to list along with table row data
trTrList.append({"name": "uncategorized", "data": trList[count]})
#now, go through each category and find specific event data
#set up local variables
tempEventListThing = []
currentEventTitle = "empty"
nextEventCount = 0
relayCount = -1
tempAthleteList = []
splits = False
splitLength = 0
tempCaptionLength = 0
currentCaptionList = []
#for each category
for secondCount in range(len(trTrList)):
#find the column count in this category
tableColumns = trTrList[secondCount]["data"].find_all("td", class_="top")
#for each column in category
for currentColumnCount in range(len(tableColumns)):
#find the table directly within column
currentColumn = tableColumns[currentColumnCount].find_all("table")[0]
#for each table row in a column (technically inside the table within the column but whatever)
for thirdCount in range(len(currentColumn.find_all("tr"))):
#either:
#title: regular, or with mulitple lines
#title with splits: funky
#caption row: includes splits if there
#data row: can contain relay objects
#getting current table row
currentRow = currentColumn.find_all("tr")[thirdCount]
#count of <th> elements
#a title has one
#a title with splits has two
#a caption row has more than two
#a data row has none
countToCheck = currentRow.find_all("th", recursive=False)
#the extra if condition is so that relay titles don't trigger this
if len(countToCheck) == 1 and len(currentRow.find_all("td")) < 1:
# title row
# if there's been a previous title, save the currently saved information in the tempAthleteList
if currentEventTitle != "empty":
temp_obj_append = {
"title": {
"name": eventName,
},
"captions": currentCaptionList,
"data": tempAthleteList
}
if splits:
temp_obj_append['splits'] = {
"length": splitLength
}
if courseID != "":
temp_obj_append['title']['courseID'] = courseID
if secondLine != "":
temp_obj_append['title']['addtl'] = secondLine
if division != "":
#print("adding division line 232 .. "+division)
temp_obj_append['title']['div'] = division
tempEventListThing.append(temp_obj_append)
#this title doesn't have splits
splits = False
#reset temp athletes (didn't do this before, disastrous)
tempAthleteList = []
# check for line breaks
secondLine = ""
if '<br/>' in str(countToCheck[0].decode_contents()):
firstLine = str(countToCheck[0].decode_contents()).split('<br/>')[0]
secondLine = str(countToCheck[0].decode_contents()).split('<br/>')[1]
currentEventTitle = str(countToCheck[0].decode_contents()).split('<br/>')
else:
firstLine = countToCheck[0].getText()
currentEventTitle = countToCheck[0].getText()
division = ""
courseID = ""
firstLineStr = firstLine
firstLine = BeautifulSoup(firstLine, "html.parser")
if firstLine.find_all("a"):
eventName = firstLine.a.getText()
division = firstLine.getText().split(" - ", 1)[0]
#print("has division line 325 - " + division)
href = firstLine.a.get("href")
if "course" in href:
courseID = href.split("course=", 1)[1].split(";", 1)[0]
#print(courseID)
#else:
#print("no course!")
else:
if " - " in firstLine:
eventName = firstLineStr.rsplit(" - ", 1)[1]
division = firstLineStr.rsplit(" - ", 1)[0]
#print("has division line 265 - "+division)
else:
eventName = firstLineStr
nextEventCount += 1
elif len(countToCheck) == 2:
# title row with splits
# if there's been a previous title, save the currently saved information in the tempAthleteList
if currentEventTitle != "empty":
temp_obj_append = {
"title": {
"name": eventName,
},
"captions": currentCaptionList,
"data": tempAthleteList
}
if splits:
temp_obj_append['splits'] = {
"length": splitLength
}
if courseID != "":
temp_obj_append['title']['courseID'] = courseID
if secondLine != "":
temp_obj_append['title']['addtl'] = secondLine
if division != "":
#print("adding division line 294 .. " + division)
temp_obj_append['title']['div'] = division
tempEventListThing.append(temp_obj_append)
#this row does have splits
splits = True
# reset temp athletes (didn't do this before, disastrous)
tempAthleteList = []
# get split length
tempCaptionLength = int(countToCheck[0]['colspan'])
# splitLength = int(countToCheck[1]['colspan'])
# check for line breaks
secondLine = ""
if '<br/>' in str(countToCheck[0].decode_contents()):
firstLine = str(countToCheck[0].decode_contents()).split('<br/>')[0]
secondLine = str(countToCheck[0].decode_contents()).split('<br/>')[1]
currentEventTitle = str(countToCheck[0].decode_contents()).split('<br/>')
else:
firstLine = countToCheck[0].getText()
currentEventTitle = countToCheck[0].getText()
division = ""
courseID = ""
firstLineStr = firstLine
firstLine = BeautifulSoup(firstLine, "html.parser")
if firstLine.find_all("a"):
eventName = firstLine.a.getText()
division = firstLine.getText().split(" - ", 1)[0]
#print("has division line 325 - " + division)
href = firstLine.a.get("href")
#hrefParse = urlparse(href)
#courseID = parse_qs(hrefParse.query)['course'][0]
if "course" in href:
courseID = href.split("course=", 1)[1].split(";", 1)[0]
#print(courseID)
#else:
#print("no course!")
else:
if " - " in firstLine:
eventName = firstLineStr.rsplit(" - ", 1)[1]
division = firstLineStr.rsplit(" - ", 1)[0]
#print("has division line 331 - " + division)
else:
eventName = firstLineStr
nextEventCount += 1
elif len(countToCheck) > 2:
# caption row
# reset previous captions
currentCaptionList = []
# print("caption row:")
# check if the current title has splits
#how many captions need to be saved
for banana in countToCheck:
currentCaptionList.append(banana.getText())
if splits:
# print("this caption has splits")
splitLength = len(currentCaptionList) - tempCaptionLength
else:
# data row
# check if current row is a relay title
if len(countToCheck) > 0:
# relay title
#find how many athletes in this relay object
#check if there are any rows at all, thanks to the one relay with nobody in it that
#caused one too many fatal errors
if currentRow.find_all("th", rowspan=True):
relayCount = (int(countToCheck[0]['rowspan']) - 1)
if relayCount == 0:
# print("there's only one person in this relay. odd.")
# pr check
if len(currentRow.find_all("td")[2].find_all("a")) > 0:
# there is a PR in this relay entry
relayAthleteObj = {
"name": currentRow.find_all("td")[1].getText(),
"id": currentRow.find_all("td")[1].a.get('href').split("=")[1],
"individual": currentRow.find_all("td")[2].b.getText().split("*")[0],
"pr": currentRow.find_all("td")[2].a.getText(),
"prID": currentRow.find_all("td")[2].a.get('href').split("=")[1]
}
elif len(currentRow.find_all("td")[2].find_all("b")) > 0 and "*" in \
currentRow.find_all("td")[2].b.getText():
relayAthleteObj = {
"name": currentRow.find_all("td")[1].getText(),
"id": currentRow.find_all("td")[1].a.get('href').split("=")[1],
"individual": currentRow.find_all("td")[2].b.getText().split("*")[0],
"pr": "PR",
}
else:
#no PR
relayAthleteObj = {
"name": currentRow.find_all("td")[1].getText(),
"id": currentRow.find_all("td")[1].a.get('href').split("=")[1],
"individual": currentRow.find_all("td")[2].getText()
}
#set up relay object
tempRelayObject = {