-
Notifications
You must be signed in to change notification settings - Fork 25
/
KillEd.py
1305 lines (1169 loc) · 62.1 KB
/
KillEd.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 os
from json import loads
from pathlib import Path
from random import randint
from secrets import MY_PASSWORD, MY_USERNAME
from time import sleep
from fuzzywuzzy import process
from bs4 import BeautifulSoup
from printy import printy
from selenium import webdriver
from selenium.common.exceptions import (ElementClickInterceptedException,
ElementNotInteractableException,
MoveTargetOutOfBoundsException,
NoSuchElementException,
NoSuchFrameException, TimeoutException)
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.ui import WebDriverWait
from webdriver_manager.chrome import ChromeDriverManager
import answers
import complimentinator
from database import syncDB, sanitize
# setup logging
logging.basicConfig(level=logging.DEBUG, format=('%(asctime)s %(levelname)s %(name)s | %(message)s'))
logger = logging.getLogger('main')
logger.setLevel(logging.DEBUG)
# sync db
syncDB()
# constants
if os.name == 'nt':
CHROME_PATH = str(Path(__file__).resolve().parents[0]) + '/drivers/chromedriver.exe'
logger.debug('using windows chromedriver')
else:
CHROME_PATH = str(Path(__file__).resolve().parents[0]) + '/drivers/chromedriver'
logger.debug('using linux chromedriver')
CLASSLINK_PATH = str(Path(__file__).resolve().parents[0]) + '/classlink.crx'
CHROME_OPTIONS = webdriver.ChromeOptions()
CHROME_OPTIONS.add_extension(CLASSLINK_PATH)
BASE_URL = "https://f2.app.edmentum.com/"
try:
driver = webdriver.Chrome(ChromeDriverManager().install(), options=CHROME_OPTIONS)
except:
driver = webdriver.Chrome(CHROME_PATH, options=CHROME_OPTIONS)
logger.debug('ChromeDriverManager failed, using local binary')
actions = ActionChains(driver)
class TableThings:
def __init__(self, webtable):
self.table = webtable
def get_row_count(self):
return len(self.table.find_elements_by_tag_name("tr")) - 1
def get_column_count(self):
return len(self.table.find_elements_by_xpath("//tr[2]/th"))
def get_table_size(self):
return {"rows": self.get_row_count(),
"columns": self.get_column_count()}
def row_data(self, row_number):
if(row_number == 0):
raise Exception("Row number starts from 1")
row_number = row_number + 1
row = self.table.find_elements_by_xpath("//tr["+str(row_number)+"]/th")
rData = []
for webElement in row:
rData.append(webElement.text)
return rData
def column_data(self, column_number):
col = self.table.find_elements_by_xpath("//tr/th["+str(column_number)+"]")
rData = []
for webElement in col:
rData.append(webElement.text)
return rData
def get_all_data(self):
# get number of rows
noOfRows = len(self.table.find_elements_by_xpath("//tr")) - 1
# logger.debug("noOfRows: " + str(noOfRows))
# get number of columns
noOfColumns = len(self.table.find_elements_by_xpath("//tr[2]/th"))
# logger.debug("noOfColumns: " + str(noOfColumns))
allData = []
# iterate over the rows, to ignore the headers we have started the i with '1'
for i in range(2, noOfRows+2):
# reset the row data every time
ro = []
# iterate over columns
for j in range(1, noOfColumns+1):
# get text from the i th row and j th column
try:
thPath = "//tr["+str(i)+"]/th["+str(j)+"]"
tdPath = "//tr["+str(i)+"]/td["+str(j)+"]"
ro.append(self.table.find_element_by_xpath(thPath).text)
# logger.debug(str(thPath)+" found")
except NoSuchElementException:
# logger.debug("//th not found, looking for //td")
ro.append(self.table.find_element_by_xpath(tdPath).text)
logger.debug(str(tdPath)+"found")
# add the row data to allData of the self.table
# logger.debug("i =" + str(i))
allData.append(ro)
return allData
def presence_of_data(self, data):
# verify the data by getting the size of the element matches based on the text/data passed
dataSize = len(self.table.find_elements_by_xpath("//th[normalize-space(text())='"+data+"']"))
presence = False
if(dataSize > 0):
presence = True
return presence
def get_cell_data(self, table, row_number, column_number):
if(row_number == 0):
raise Exception("Row number starts from 1")
row_number = row_number+1
cellData = table.find_element_by_xpath("//tr["+str(row_number)+"]/th["+str(column_number)+"]").text
return cellData
def getAssignments():
WebDriverWait(driver, 10).until(lambda driver: expected_conditions.presence_of_element_located((By.CLASS_NAME, 'assignmentName')))
page_source = driver.page_source
soup = BeautifulSoup(page_source, 'lxml')
assignments = []
assignment_selector = soup.find_all('div', class_='assignment isotope-item')
for assignment_selector in assignment_selector:
name = assignment_selector.find('div', class_='assignmentName').get_text()
name = " ".join(name.splitlines()) # remove weird newlines
try:
name = name.split("- ", 1)[1]
name = name.split(" - Period", 1)[0]
except:
pass
url = assignment_selector.find('a').get('href')
assignment = {"name": name, "url": url}
assignments.append(assignment)
return assignments
def assignmentSelect(assignments):
theEntireAlphabet = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']
theAvailableAlphabet = []
for letter in theEntireAlphabet:
theAvailableAlphabet.append(letter)
if len(theAvailableAlphabet) == len(assignments):
break
i = 0
for assignment in assignments:
printy(f'[n>]\[{theAvailableAlphabet[assignments.index(assignment)]}\]@ {assignment["name"]}')
i += 1
while True:
selectLet = input('Choose an assignment: ').upper()
if selectLet in theAvailableAlphabet:
break
else:
printy('\nError: Invalid Character', 'r')
selection = theAvailableAlphabet.index(selectLet)
printy(f'Chose {assignments[selection]["name"]}', 'n')
driver.get(BASE_URL + assignments[selection]['url'])
def openCourse():
# find/open started unit, then if one cant be found find/open new unit
sortInProgress = "//li[@id='tab-inprogress']"
# WebDriverWait(driver, 10).until(lambda driver: driver.find_element_by_xpath("//li[@id='tab-inprogress']"))
sortNotMastered = "//li[@id='tab-completed-not-mastered']"
# WebDriverWait(driver, 10).until(lambda driver: driver.find_element_by_xpath("//li[@id='tab-completed-not-mastered']"))
sortNotStarted = "//li[@id='tab-notstarted']"
# WebDriverWait(driver, 10).until(lambda driver: driver.find_element_by_xpath("//li[@id='tab-notstarted']"))
# we are currently above the array
sortArray = [sortInProgress, sortNotMastered, sortNotStarted]
for sort in sortArray:
WebDriverWait(driver, 10).until(expected_conditions.element_to_be_clickable((By.XPATH, sort))).click()
sleep(1)
try:
tutOpen = False
try:
logger.debug("looking for path 2 of x")
coursePATH = "//span[contains(text(), '2 of ')]"
coursesArray = WebDriverWait(driver, 1).until(lambda driver: driver.find_elements_by_xpath(coursePATH))
for course in coursesArray:
try:
driver.execute_script("arguments[0].scrollIntoView({behavior: 'smooth', block: 'center' });", course)
course.click()
except (ElementNotInteractableException, ElementClickInterceptedException, TimeoutException):
logger.error("wrong course")
else:
openTut()
tutOpen = True
break
if tutOpen == False:
raise ElementNotInteractableException
except (ElementNotInteractableException, ElementClickInterceptedException, TimeoutException):
try:
logger.debug("looking for path 1 of x")
coursePATH = "//span[contains(text(), '1 of ')]"
coursesArray = WebDriverWait(driver, 1).until(lambda driver: driver.find_elements_by_xpath(coursePATH))
for course in coursesArray:
try:
driver.execute_script("arguments[0].scrollIntoView({behavior: 'smooth', block: 'center' });", course)
course.click()
except (ElementNotInteractableException, ElementClickInterceptedException, TimeoutException):
logger.error("wrong course")
else:
openTut()
tutOpen = True
break
if tutOpen == False:
raise ElementNotInteractableException
except (ElementNotInteractableException, ElementClickInterceptedException, TimeoutException):
try:
logger.debug("looking for path 0 of x")
coursePATH = "//span[contains(text(), '0 of ')]"
coursesArray = WebDriverWait(driver, 1).until(lambda driver: driver.find_elements_by_xpath(coursePATH))
for course in coursesArray:
try:
driver.execute_script("arguments[0].scrollIntoView({behavior: 'smooth', block: 'center' });", course)
course.click()
except (ElementNotInteractableException, ElementClickInterceptedException, TimeoutException):
logger.error("wrong course")
else:
openTut()
tutOpen = True
break
if tutOpen == False:
raise ElementNotInteractableException
except (ElementNotInteractableException, ElementClickInterceptedException, TimeoutException):
# tries to open courses athat are a different type
try:
# looks for all activities
activityArray = driver.find_elements_by_xpath("//span[@class='ico oneSheetIco']")
for activity in activityArray:
try:
# scrolls to possible activity
driver.execute_script("arguments[0].scrollIntoView({behavior: 'smooth', block: 'center' });", activity)
activity.click()
except (ElementClickInterceptedException, ElementNotInteractableException, NoSuchElementException):
# if activity can't open it tries the next one in the array
pass
else:
logger.debug("activity opened")
# WebDriverWait(driver, 10).until(lambda driver: driver.find_element_by_xpath("//body[@class='player-body']"))
try:
# sees if prgm is in Tut
logger.debug("im going to kms")
WebDriverWait(driver, 10).until(expected_conditions.element_to_be_clickable((By.XPATH, "//button[@class='tutorial-nav-next']")))
tutArray = WebDriverWait(driver, 1).until(lambda driver: driver.find_elements_by_xpath("//*[contains(text(), 'Tutorial')]"))
logger.debug("im not joking")
if len(tutArray) < 2:
logger.debug("this is the last straw")
raise NoSuchElementException
except NoSuchElementException:
try:
# checks if prgm is in Practice
logger.debug("why am i here")
WebDriverWait(driver, 5).until(lambda driver: driver.find_element_by_xpath("//*[contains(text(), 'Practice')]"))
except NoSuchElementException:
try:
# checks if prgm is in Test
WebDriverWait(driver, 5).until(lambda driver: driver.find_element_by_xpath("//*[contains(text(), 'Test')]"))
testArray = WebDriverWait(driver, 1).until(lambda driver: driver.find_elements_by_xpath("//*[contains(text(), 'Test')]"))
if len(testArray) < 2:
raise NoSuchElementException
except NoSuchElementException:
logger.error("No one should see this... Ever.")
else:
# runs complete test
completeMasteryTest()
else:
# runs complete prac
completePractice()
else:
# runs complete tut
completeTut()
except:
logger.debug("not menu type 2")
pass
else:
logger.debug("Found Course (0 of x)")
break
else:
logger.debug("Found Course (1 of x)")
break
else:
logger.debug("Found Course (2 of x)")
break
except SyntaxError:
logger.error("if this runs imma kms")
try:
logger.debug:("No Courses Found")
except:
pass
# def openCourseType2():
# logger.debug("in CourseType2")
# # find/open started unit, then if one cant be found find/open new unit
# sortInProgress = WebDriverWait(driver, 1).until(lambda driver: driver.find_element_by_xpath("//li[@id='tab-inprogress']"))
# sortNotMastered = WebDriverWait(driver, 1).until(lambda driver: driver.find_element_by_xpath("//li[@id='tab-completed-not-mastered']"))
# sortNotStarted = WebDriverWait(driver, 1).until(lambda driver: driver.find_element_by_xpath("//li[@id='tab-notstarted']"))
# # we are currently above the array
# sortArray = [sortInProgress, sortNotMastered,sortNotStarted]
# sleep(1)
# for sort in sortArray:
# sort.click() # this one
# logger.debug("sorting")
# try:
# # looks for all activities
# activityArray = driver.find_elements_by_xpath("//span[@class='ico oneSheetIco']")
# for activity in activityArray:
# try:
# # scrolls to possible activity
# driver.execute_script("arguments[0].scrollIntoView({behavior: 'smooth', block: 'center' });", activity)
# activity.click()
# # this is the click?
# # yeaj its not this one lol good luck
# # i think but then again im realizing term says sort.click() nut like that was working fine so idk
# # cool im retarded
# # like it errors but then still opens it, but when i used the other kind of click. it just didnt open
# except (ElementClickInterceptedException, ElementNotInteractableException, NoSuchElementException, TimeoutException):
# # if activity can't open it tries the next one in the array
# pass
# else:
# logger.debug("activity opened")
# # WebDriverWait(driver, 10).until(expected_conditions.element_to_be_clickable((By.XPATH, "//body[@class='player-body']"))).click()
# try:
# # sees if prgm is in Tut
# WebDriverWait(driver, 1).until(lambda driver: driver.find_element_by_xpath("//h1//thspan[contains(text(), 'Tutorial')]"))
# except (NoSuchElementException, TimeoutException):
# try:
# # checks if prgm is in Practice
# WebDriverWait(driver, 1).until(lambda driver: driver.find_element_by_xpath("//li[contains(text(), 'Practice')]"))
# except (NoSuchElementException, TimeoutException):
# try:
# # checks if prgm is in Test
# WebDriverWait(driver, 1).until(lambda driver: driver.find_element_by_xpath("//li[contains(text(), 'Test')]"))
# except (NoSuchElementException, TimeoutException):
# logger.error("No one should see this... Ever.")
# else:
# # runs complete test
# completeMasteryTest()
# else:
# # runs complete prac
# completePractice()
# else:
# # runs complete tut
# logger.debug("fucking how, what")
# completeTut()
# except:
# logger.debug("not menu type 2")
# pass
def openTut():
try:
tutorialBtnArray = driver.find_elements_by_xpath("//span[contains(text(), 'Tutorial')]")
for tutorialBtn in tutorialBtnArray:
try:
driver.execute_script("arguments[0].scrollIntoView({behavior: 'smooth', block: 'center' });", tutorialBtn)
WebDriverWait(driver, 1).until(expected_conditions.element_to_be_clickable((By.ID, tutorialBtn)))
except (TimeoutException, NoSuchElementException, ElementClickInterceptedException):
logger.debug("moving on to next tut")
else:
print("opened tutorial")
tutorialBtn = tutorialBtn
break
except NoSuchElementException:
logger.debug("Tutorial Not Found")
else:
logger.debug("is tut complete?")
try:
try:
logger.debug("looking for finished icon")
WebDriverWait(driver, .5).until(expected_conditions.element_to_be_clickable((By.XPATH, "//span[@class='ico finishedBigIco']")))
except TimeoutException:
logger.debug("looking for expemt icon")
WebDriverWait(driver, .5).until(expected_conditions.element_to_be_clickable((By.XPATH, "//span[@class='ico exemptBigIco]'")))
except TimeoutException:
tutorialBtn.click()
logger.debug("Tutorial Opened")
else:
logger.debug("Tutorial Already Complete")
try:
# OPEN PRACTICE
openPractice()
except EnvironmentError:
logger.debug('Attempting to Open Test')
try:
openMasteryTest()
except SyntaxError as err:
logger.error(err)
closeCourseBtnArray = driver.find_elements_by_xpath("//span[@class='ico closeCardIco']")
i = 0
for closeCourseBtn in closeCourseBtnArray:
i += 1
try:
# is clickable?
closeCourseBtn.click()
except ElementClickInterceptedException:
logger.debug('closeCourseBtn not clickable')
else:
logger.debug('closeCourseBtn is clickable')
break
raise ElementNotInteractableException
def completeTut():
WebDriverWait(driver, 10).until(lambda driver: driver.find_element_by_xpath("//header[@class='tutorial-viewport-header']"))
while True:
try:
# is navNext disabled?
driver.switch_to.parent_frame()
# driver.find_element_by_xpath("//button[@class='tutorial-nav-next']")
WebDriverWait(driver, 1).until(expected_conditions.element_to_be_clickable((By.XPATH, "//button[@class='tutorial-nav-next']"))).click()
logger.debug('navNext is not disabled, moving to next')
completeTut()
except:
logger.debug('navNext is disabled, work to be done..')
isFRQ()
isMPC()
isMultipageSlide()
isAnswerBtn()
isAnswerBtn2()
isAnswerBtn3()
isAnswerBtn4()
isAnswerBtn5()
isOrderedProblemChoice()
isFinished()
def openPractice():
try:
practiceBtn = driver.find_element_by_xpath("//span[contains(text(), 'Practice')]")
driver.execute_script("arguments[0].scrollIntoView({behavior: 'smooth', block: 'center' });", practiceBtn)
try:
finsihedIconArray = driver.find_elements_by_xpath("//span[@class='ico finishedBigIco']")
except NoSuchElementException:
pass
else:
if len(finsihedIconArray) == 2:
logger.debug("Practice Already Complete")
raise EnvironmentError
WebDriverWait(driver, 10).until(expected_conditions.element_to_be_clickable((By.XPATH, "//span[contains(text(), 'Practice')]"))).click()
except (NoSuchElementException, ElementClickInterceptedException, ElementNotInteractableException, EnvironmentError):
logger.debug("No Unfinished Practice Found")
raise EnvironmentError
else:
completePractice()
def completePractice():
logger.debug("completePractice()")
while True:
try:
btnClicked = False
# creates array of the end btn
endBtnArray = driver.find_elements_by_xpath("//a[@class='player-button worksheets-endsession']")
for endBtn in endBtnArray:
# cycles through to check if any work, meaning we have reached the end of the test
try:
driver.execute_script("arguments[0].scrollIntoView({behavior: 'smooth', block: 'center' });", endBtn)
endBtn.click()
except (NoSuchElementException, ElementClickInterceptedException, ElementNotInteractableException):
pass
else:
logger.debug("end btn clicked")
sleep(.5)
# btn is clicked so it breaks and continues on
btnClicked = True
break
if btnClicked == False:
raise EnvironmentError
except (NoSuchElementException, ElementClickInterceptedException, ElementNotInteractableException, EnvironmentError):
# cant end test since theres questions to answer
try:
# clicks mpc option
mpc = False
mpcOptionArray = driver.find_elements_by_xpath("//div[@class='multichoice-choice']")
for mpcOption in mpcOptionArray:
# Cycles through mpc options
try:
mpcOption.click()
except (NoSuchElementException, ElementNotInteractableException, ElementClickInterceptedException):
pass
else:
mpc = True
break
if mpc == False:
raise EnvironmentError
except EnvironmentError:
logger.debug("not a mpc question")
# trys to answer dropdown question
try:
dropD = False
driver.find_element_by_xpath("//select[@class='dropdown']")
dropdownArray = driver.find_elements_by_xpath("//select[@class='dropdown']")
except NoSuchElementException:
try:
logger.debug("drag and also drop?")
driver.find_element_by_xpath("//div[@data-dropped='false']")
except NoSuchElementException:
logger.debug("not drag and also drop")
try:
logger.debug("frq")
driver.find_element_by_xpath("//input[@spellcheck='false']")
except NoSuchElementException:
logger.debug("not frq")
else:
textbox = driver.find_element_by_xpath("//input[@spellcheck='false']")
textbox.click()
textbox.send_keys(".")
# submits answer
logger.debug("submit time")
subBtnArray = driver.find_elements_by_xpath("//a[@class='player-button worksheets-submit']")
for subBtn in subBtnArray:
# cycles through subBtns
driver.execute_script("arguments[0].scrollIntoView({behavior: 'smooth', block: 'center' });", subBtn)
subBtn.click()
try:
# if the answers correct (or its second failed attemt), next btn is shown and can be clicked
nextBtnArray = driver.find_elements_by_xpath("//a[@class='player-button worksheets-next']")
for nextBtn in nextBtnArray:
try:
driver.execute_script("arguments[0].scrollIntoView({behavior: 'smooth', block: 'center' });", nextBtn)
nextBtn.click()
except (ElementNotInteractableException, ElementClickInterceptedException):
pass
else:
# moves onto next question
break
# if all next btns dont work the answer wasnt correct and it tries again
try:
retryBtnArray = driver.find_elements_by_xpath("//a[@class='player-button worksheets-retry']")
for retryBtn in retryBtnArray:
try:
retryBtn.click()
except(NoSuchElementException, ElementClickInterceptedException, ElementNotInteractableException):
pass
else:
break
except:
pass
except:
pass
else:
driver.find_element_by_xpath("//div[@data-dropped='false']")
try:
driver.find_element_by_xpath("//div[@class='droppable target ui-droppable']")
except NoSuchElementException:
try:
driver.find_element_by_xpath("//li[@class='droppable ui-droppable']")
except NoSuchElementException:
logger.debug("no drops found")
else:
dropArray = driver.find_element_by_xpath("//li[@class='droppable ui-droppable']")
else:
dropArray = driver.find_elements_by_xpath("//div[@class='droppable target ui-droppable']")
# drags element to a droppable
dragArray = driver.find_elements_by_xpath("//div[@data-dropped='false']")
i=0
for dropElm in dropArray:
dragElm = dragArray[i]
ActionChains(driver).drag_and_drop(dragElm, dropElm).perform()
i+=1
# submits answer
logger.debug("submit time")
subBtnArray = driver.find_elements_by_xpath("//a[@class='player-button worksheets-submit']")
for subBtn in subBtnArray:
# cycles through subBtns
try:
driver.execute_script("arguments[0].scrollIntoView({behavior: 'smooth', block: 'center' });", subBtn)
subBtn.click()
except:
pass
else:
break
try:
# if the answers correct (or its second failed attemt), next btn is shown and can be clicked
nextBtnArray = driver.find_elements_by_xpath("//a[@class='player-button worksheets-next']")
for nextBtn in nextBtnArray:
try:
driver.execute_script("arguments[0].scrollIntoView({behavior: 'smooth', block: 'center' });", nextBtn)
nextBtn.click()
except (ElementNotInteractableException, ElementClickInterceptedException):
pass
else:
# moves onto next question
break
# if all next btns dont work the answer wasnt correct and it tries again
try:
retryBtnArray = driver.find_elements_by_xpath("//a[@class='player-button worksheets-retry']")
for retryBtn in retryBtnArray:
try:
retryBtn.click()
except(NoSuchElementException, ElementClickInterceptedException, ElementNotInteractableException):
pass
else:
break
except:
pass
except:
pass
else:
try:
logger.debug("drop down")
for dropdown in dropdownArray:
try:
dropdown.click()
except (ElementNotInteractableException, ElementClickInterceptedException):
logger.debug("not drop down")
else:
# if box can be clicked it scrolls down and selects first choice
dropdown.send_keys(Keys.DOWN)
dropdown.send_keys(Keys.RETURN)
dropD = True
if dropD == False:
raise EnvironmentError
except EnvironmentError:
pass
else:
# submits answer
logger.debug("submit time")
subBtnArray = driver.find_elements_by_xpath("//a[@class='player-button worksheets-submit']")
for subBtn in subBtnArray:
# cycles through subBtns
try:
driver.execute_script("arguments[0].scrollIntoView({behavior: 'smooth', block: 'center' });", subBtn)
subBtn.click()
except:
pass
else:
break
try:
# if the answers correct (or its second failed attemt), next btn is shown and can be clicked
nextBtnArray = driver.find_elements_by_xpath("//a[@class='player-button worksheets-next']")
for nextBtn in nextBtnArray:
try:
driver.execute_script("arguments[0].scrollIntoView({behavior: 'smooth', block: 'center' });", nextBtn)
nextBtn.click()
except (ElementNotInteractableException, ElementClickInterceptedException):
pass
else:
# moves onto next question
break
# if all next btns dont work the answer wasnt correct and it tries again
try:
retryBtnArray = driver.find_elements_by_xpath("//a[@class='player-button worksheets-retry']")
for retryBtn in retryBtnArray:
try:
retryBtn.click()
except(NoSuchElementException, ElementClickInterceptedException, ElementNotInteractableException):
pass
else:
break
except:
pass
except:
pass
else:
# submits answer
logger.debug("submit time")
subBtnArray = driver.find_elements_by_xpath("//a[@class='player-button worksheets-submit']")
for subBtn in subBtnArray:
# cycles through subBtns
try:
driver.execute_script("arguments[0].scrollIntoView({behavior: 'smooth', block: 'center' });", subBtn)
subBtn.click()
except:
pass
else:
break
try:
# if the answers correct (or its second failed attemt), next btn is shown and can be clicked
nextBtnArray = driver.find_elements_by_xpath("//a[@class='player-button worksheets-next']")
for nextBtn in nextBtnArray:
try:
driver.execute_script("arguments[0].scrollIntoView({behavior: 'smooth', block: 'center' });", nextBtn)
nextBtn.click()
except (ElementNotInteractableException, ElementClickInterceptedException):
pass
else:
# moves onto next question
break
# if all next btns dont work the answer wasnt correct and it tries again
try:
retryBtnArray = driver.find_elements_by_xpath("//a[@class='player-button worksheets-retry']")
for retryBtn in retryBtnArray:
try:
retryBtn.click()
except(NoSuchElementException, ElementClickInterceptedException, ElementNotInteractableException):
pass
else:
break
except:
pass
except:
pass
else:
# end btn was pressed,
logger.debug("Practice Complete")
# finds/clicks exit btn
WebDriverWait(driver, 10).until(driver.find_element_by_xpath("//div[@class='results-header-text']"))
exitBtn = driver.find_element_by_xpath("//button[@title='Exit']")
exitBtn.click()
# finds/clicks okay btn
okBtnElm = WebDriverWait(driver, 10).until(driver.find_element_by_xpath("//span[contains(text(), 'OK')]"))
driver.execute_script("arguments[0].click()", okBtnElm)
break
def openMasteryTest():
try:
masterytestBtn = driver.find_element_by_xpath("//span[contains(text(), 'Mastery Test')]")
driver.execute_script("arguments[0].scrollIntoView({behavior: 'smooth', block: 'center' });", masterytestBtn)
WebDriverWait(driver, 10).until(expected_conditions.element_to_be_clickable((By.XPATH, "//span[contains(text(), 'Mastery Test')]"))).click()
except NoSuchElementException:
logger.debug("Mastery Test Not Found")
else:
logger.debug("Mastery Test Opened")
completeMasteryTest()
def completeMasteryTest():
try:
startTestBtn = WebDriverWait(driver, 2).until(lambda driver: driver.find_element_by_xpath("//button[@class='mastery-test-start']"))
except TimeoutException:
startTestBtn = WebDriverWait(driver, 2).until(lambda driver: driver.find_element_by_xpath("//button[@class='level-assessment-start']"))
logger.debug("starting test")
startTestBtn.click()
questionCountArray = driver.find_elements_by_xpath("//li[@class='drop-menu-item']")
questionCount = len(questionCountArray) + 1
print("Questions: " + str(questionCount))
sleep(1)
for _ in range(questionCount):
WebDriverWait(driver, 4).until(lambda driver: driver.find_element_by_xpath("//div[@class='questions-container']"))
# from the whole page, find just the question-revelvent html
wholePageSoup = BeautifulSoup(driver.page_source, 'lxml')
questionContainer = wholePageSoup.find('div', {'class': 'questions-container'})
questionSoup = BeautifulSoup(str(questionContainer), 'lxml')
# figure out which type of question we're in
if len(questionSoup.findAll('div', {'class': 'draggable-item'})) != 0: # if its a drag and drop
logger.debug('drag and drop format')
questionType = 'drag'
question = sanitize(questionSoup.find('div', {'class': 'stem'}).text)
# grab the draggables
draggablesText = questionSoup.findAll('li', {'class': 'draggable-container'})
draggablesElement = driver.find_elements_by_xpath("//li[@class='draggable-container']")
for i in draggablesText:
draggablesText[draggablesText.index(i)] = sanitize(i.text)
logger.debug(f'draggables: {draggablesText}')
# grab the locations the drags can go to
dropLocationsElement = driver.find_elements_by_xpath("//li[@class='droppable ui-droppable']")
dropLocationsText = questionSoup.findAll('ul', {'class': 'droppable-wrapper'})
for i in dropLocationsText:
dropLocationsText[dropLocationsText.index(i)] = sanitize(i.text)
answerFound = answers.query(question, questionType, draggablesText)
for answer in answerFound:
draggableToMove = draggablesElement[draggablesText.index(answer['drag'])]
actions.drag_and_drop(draggableToMove, dropLocationsElement[dropLocationsText.index(answer['match'])])
elif len(questionSoup.findAll('div', {'class': 'text-entry'})) != 0: # text entry format
logger.debug('text entry format')
questionType = 'text'
question = sanitize(questionSoup.find('div', {'class': 'stem'}).text)
inputBox = driver.find_element_by_xpath("//input[@class='textentry-input']")
answerFound = answers.query(question, questionType)['answer'][0]
logger.debug(f'text ans: {answerFound}')
inputBox.click()
inputBox.send_keys(answerFound)
elif len(questionSoup.findAll('select', {'class': 'inlinechoice-select'})) != 0: # if its a dropdown
logger.debug("dropdown format")
questionType = 'dropdown'
question = sanitize(questionSoup.find('div', {'class': 'inline-choice-content interactive-content-block'}).text)
query = answers.query(question, questionType)
answerFound = query['answer']
dropdownboxArray = driver.find_elements_by_xpath("//select[@class='inlinechoice-select']")
i = 0
logger.debug(f'found {len(dropdownboxArray)} dropdowns')
for dropdown in dropdownboxArray:
dropdown.click()
dropdown.send_keys(answerFound[i])
dropdown.send_keys(Keys.ENTER)
i += 1
# multiple choice stuff
else:
# find the multiple choice question
possibleQuestionElements = []
possibleQuestionElements.extend(questionSoup.findAll('div', {'class': 'stem'}))
# possibleQuestionElements.extend(questionSoup.findAll('div', {'class': 'prompt visible'}))
possibleQuestions = []
for element in possibleQuestionElements:
if element.text.count('?') != 0 or element.text.lower().count('which') != 0 or element.text.lower().count('what') != 0 or element.text.lower().count('who') or element.text.lower().count('match') or element.text.lower().count('select') != 0 or element.text.lower().count('decide') != 0:
possibleQuestions.append(element.text)
question = ""
# if the question is spliced up, this should fix it (?)
for possibleQuestion in possibleQuestions:
question += possibleQuestion
# remove weird nonsense from question
question = question.replace('Select the correct answer.', '')
question = question.replace('Select all the correct answers.', '')
question = sanitize(question)
logger.debug(question)
# answer the question
# multichoice format, most classes
if len(questionSoup.findAll('div', {'class': 'multichoice-choice'})) != 0:
logger.debug('multichoice format')
answerChoicesElement = driver.find_elements_by_class_name('multichoice-choice')
answerChoicesText = questionSoup.findAll('div', {'class': 'multichoice-choice'})
for i in answerChoicesText:
answerChoicesText[answerChoicesText.index(i)] = sanitize(i.text)
logger.debug('answer choices '+ str(answerChoicesText))
# if its a multiresponse (checkboxes)
elif len(questionSoup.findAll('div', {'class': 'multiresponse'})) != 0:
logger.debug('checkbox format')
answerChoicesElement = driver.find_elements_by_class_name('multiresponse-choice')
answerChoicesText = questionSoup.findAll('li', {'class': 'multiresponse-choice'})
for i in answerChoicesText:
answerChoicesText[answerChoicesText.index(i)] = sanitize(i.text)
logger.debug('answer choices '+ str(answerChoicesText))
# ht interaction format, usually for english
elif len(questionSoup.findAll('span', {'class': 'ht-interaction'})) != 0:
logger.debug('ht interaction format')
answerChoicesElement = driver.find_elements_by_class_name('ht-interaction')
answerChoicesText = questionSoup.findAll('span', {'class': 'ht-interaction'})
for i in answerChoicesText:
answerChoicesText[answerChoicesText.index(i)] = sanitize(i.text)
logger.debug('answer choices ' + str(answerChoicesText))
# get the answer to the question then find its closest match out of our choices
for answer in answers.query(question, 'mcq')['answer']:
answerCorrect = process.extractOne(answer, answerChoicesText)[0]
answerChoicesElement[answerChoicesText.index(answerCorrect)].click()
logger.debug(f'answer: {answerCorrect}')
sleep(.5)
nextBtn = driver.find_element_by_xpath("//a[@class='player-button worksheets-submit' and contains(text(),'Next')]")
nextBtn.click()
sleep(1)
logger.debug("done with test")
syncDB()
okBtn = driver.find_element_by_xpath("//span[@class='ui-button-text' and contains(text(),'OK')]")
okBtn.click()
WebDriverWait(driver, 10).until(expected_conditions.element_to_be_clickable((By.XPATH, "//button[@type='button' and contains(text(),'Close and return to your activities')]"))).click()
def BigBoyTest():
try:
bbTestOpen = False
bbTestArray = driver.find_elements_by_xpath("//span[@class='ico testIco']")
for bbTest in bbTestArray:
try:
print(bbTest)
bbTest.click()
except (ElementClickInterceptedException, ElementNotInteractableException):
logger.debug("big boy test is not clickable")
else:
logger.debug("big boy test is clickable")
bbTestOpen = True
break
if bbTestOpen == False:
raise SyntaxError
except SyntaxError:
print("No Big Tests Found")
else:
logger.debug("Mastery Test Opened")
completeMasteryTest()
def isFRQ():
try:
driver.find_element_by_id("content-iframe")
driver.switch_to.frame("content-iframe")
logger.debug("switched to frame")
driver.find_elements_by_xpath('//*[@title="Rich Text Area. Press ALT-F9 for menu. Press ALT-F10 for toolbar. Press ALT-0 for help"]')
except NoSuchElementException:
logger.debug("is not FRQ")
else:
logger.debug("is FRQ")
# use lxml to execute the xpath to see if these are fake frames
soup = BeautifulSoup(driver.page_source, 'lxml')
frqFramesSoup = soup.findAll('textarea', {'class': 'responseText'})
logger.debug(str(len(frqFramesSoup)) + " FRQs Found")
if len(frqFramesSoup) == 0:
driver.switch_to.parent_frame()
return
frqFrames = driver.find_elements_by_xpath('//*[@title="Rich Text Area. Press ALT-F9 for menu. Press ALT-F10 for toolbar. Press ALT-0 for help"]')
try:
try:
driver.find_element_by_xpath("//button[@class='btn buttonCorrectToggle' and @style='display:none;']")
except NoSuchElementException:
logger.debug("well fuck ig")
else:
showAnswerBtnArray = driver.find_elements_by_xpath("//button[@class='btn buttonCorrectToggle' and @style='display:none;']")
for showAns in showAnswerBtnArray:
driver.execute_script("arguments[0].click()", showAns)
except:
logger.debug("No show answer btns")
try:
logger.debug("looking for btn")
driver.find_element_by_xpath("//button[@class='btn buttonDone' and @style='']")
except NoSuchElementException:
logger.debug("no btns found or all buttons pressed, hopefully..")
else:
logger.debug("found btn")
submitBtnElmArray = WebDriverWait(driver, 10).until(lambda driver: driver.find_elements_by_xpath("//button[@class='btn buttonDone' and @style='']"))
for submitBtnElm in submitBtnElmArray:
logger.debug("scroll to btn")
driver.execute_script("arguments[0].scrollIntoView({behavior: 'smooth', block: 'center' });", submitBtnElm)
driver.execute_script("arguments[0].click()", submitBtnElm)
sleep(.5)
driver.switch_to.parent_frame()
logger.debug("FRQ(s) Answered")
def isMPC():
try:
driver.find_element_by_id("content-iframe")
logger.debug("switched to i frame")
driver.switch_to.frame("content-iframe")
driver.find_element_by_id("mcqChoices")
except NoSuchElementException:
logger.debug("is not MPC")
driver.switch_to.parent_frame()
else:
logger.debug("is MPC")
script = driver.find_element_by_xpath("//script[contains(.,'IsCorrect')]").get_attribute("innerHTML")
# logger.debug(script + '\n')
scriptElmCut = script[20:-2]
# logger.debug(scriptElmCut + '\n')
parsedScript = loads(scriptElmCut)
theEntireNumabet = ['0', '1', '2', '3']
i = 0
for choice in parsedScript['Choices']: # this goes thru all the choices
if choice['IsCorrect']: # if the isCorrect bool is True, then the answer is correct
logger.debug('the answer is ' + theEntireNumabet[i])
ans = theEntireNumabet[i]