from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from selenium.common.exceptions import NoSuchElementException,StaleElementReferenceException,ElementNotVisibleException,TimeoutException,WebDriverException
import time
import os
import sys
import re
from datetime import date
def BeforeEndDate():
endate=date(SetYear,SetMonth,SetDay)
stdate=date.today()
isReg=(stdate<=endate)
if isReg:
print("程序有效期至:"+str(endate)+'\n')
return True
else:
try:
print("程序過期!")
#os._exit(0)
return False
except:
return False
def SaveAnswer(txtlist):
f=open(dbPath,'a+')
print(txtlist)
f.writelines(txtlist)
f.close()
def GetListFrom(txtPath):
txtlist=[]
with open(txtPath,'r',encoding = 'utf-8') as file_object:
lines=set(file_object.readlines())
for index,line in enumerate(lines):
oneline=line.strip()
txtlist.append(oneline)
return txtlist
def JoinFolderpath(filepath):#獲取文件釋放路徑
try:
base_path = sys._MEIPASS
except:
base_path=os.path.abspath('.')
fp=os.path.join(base_path, filepath)
return fp
def GetQnaDic():
dic={}
fp=JoinFolderpath(eaxmPath)
txtlist=GetListFrom(fp)
for oneline in txtlist:
if "=" in oneline:
que=oneline.split('=')[0]
an=oneline.split('=')[1]
dic[que]=an
return dic
def EmKeytext(xpath,txt=""):
if EmPresence(xpath):
em=dr.find_element_by_xpath(xpath)
em.clear()
em.send_keys(txt)
return True
else:
return False
def EmPresence(xpath,duration=10,msg=""):
wait=WebDriverWait(dr,duration)
locator=(By.XPATH,xpath)
try:
em=wait.until(EC.visibility_of_element_located(locator))
return True
except:
return False
def EmLenth(xpath):
try:
ems=dr.find_elements_by_xpath(xpath)
return len(ems)
except:
return 0
def ClickEm(xpath,index=0,scroll=False,sleeptime=10,btnCaption="按鈕"):
try:
btn=dr.find_elements_by_xpath(xpath)[index]
print('定位'+btnCaption+str(index+1)+'成功')
if scroll==True:
try:
dr.execute_script("return arguments[0].scrollIntoView();",btn)
time.sleep(1)
print('滾屏到【'+btnCaption+str(index+1)+'】成功')
except:
print('滾屏到【'+btnCaption+str(index+1)+'】失敗')
try:
dr.execute_script("arguments[0].click();",btn)
print('單擊【'+btnCaption+'】['+str(index+1)+']成功')
time.sleep(sleeptime)
return True
except:
print('單擊【'+btnCaption+str(index+1)+'】失敗')
return False
except:
print('定位'+btnCaption+str(index+1)+'失敗')
return False
def Login():
u_xpath='//input[@id=""]'
if EmKeytext(u_xpath,USER):
print('輸入用戶名')
p_xpath='//input[@id=""]'
if EmKeytext(p_xpath,PSWD):
print('輸入密碼')
v_xpath='//input[@id=""]'
if EmKeytext(v_xpath):
print('清空驗證碼')
f_xpath='//"]'
print('請在20秒內輸入驗證碼並登陸')
if EmPresence(f_xpath,20):
print('登陸成功')
return True
print('登陸失敗')
return False
def SwithNewPage():
handles=dr.window_handles
newPage=dr.window_handles[len(handles)-1]
try:
dr.switch_to_window(newPage)
print('切換窗口成功')
return True
except:
print('切換窗口失敗')
return False
#裝飾器 用於裝飾:需要打開新窗口並返回原窗口的函數
def SwithTab(study):
def inner(mainHandle):
print('do something before function '+study.__name__)
SwithNewPage()
time.sleep(3)
print("裝飾器內 執行函數: "+study.__name__)
study(mainHandle)
print('do some thing after function '+study.__name__)
if dr.current_window_handle!=mainHandle:
dr.close()
time.sleep(2)
SwithNewPage()
dr.refresh()
time.sleep(3)
return inner
def WatchVideo(secHandle):
xpath='//td[contains(text(),"要求學習時長")]'
if EmPresence(xpath,20):
xpath='//span[starts-with(@class,"") and not(text()="")]'
undoCount=EmLenth(xpath)
while undoCount>0:
ClickEm(xpath=xpath,index=0,scroll=False,sleeptime=3,btnCaption="觀看第一個視頻")
xpath='//div[@class="prism-big-play-btn"]
ClickEm(xpath=xpath,index=0,scroll=False,sleeptime=3,btnCaption="播放大按鈕")
counter=0
while CheckVideo()==False:
counter=counter+1
if counter==600:
break
time.sleep(5)
undoCount=EmLenth(xpath)
def CheckVideo():#針對觀看視頻過程中出現的問題進行處理
isdone=False
try:
xpath='//span/span[text()="已完成"]'
pre=EmPresence(xpath)
if pre:
return True
except:
return False
def LoopStudyVideo():#進入課程,循環所有課程,觀看視頻
xpath='//td[@class="mycourse-row-operate"]/a[contains(text(),"進入課程") or contains(text(),"開始學習")]'
courseCount=EmLenth(xpath)
mainHandle=dr.current_window_handle #保留窗口句柄
for x in range(courseCount):
ClickEm(xpath=xpath,index=x,scroll=False,sleeptime=3,btnCaption="進入課程 或 開始學習")#此處注意,觀看視頻index需要遞增,因為還為考試仍然顯示可學
StudyVideo(mainHandle)
def LoopHomework():
xpath='//td[@class="mycourse-row-operate"]/a[contains(text(),"") or contains(text(),"")]'
courseCount=EmLenth(xpath)
mainHandle=dr.current_window_handle #保留窗口句柄
for x in range(courseCount):
ClickEm(xpath=xpath,index=0,scroll=False,sleeptime=3,btnCaption="進入課程 或 開始學習")#此處注意INdex一直是0 ,因為測試結束后返回,課程已經完成。index發生了變化
#TryHomework(mainHandle)
FinishHomework(mainHandle)
@SwithTab
def StudyVideo(mainHandle):
xpath='//a[@class="course-intro-btn course-intro-footer-btn button-enable" and contains(text(),"")]'
duration=10
if EmPresence(xpath):
xpath='//li/a/span[contains(text(),"未")]'
undoneCount=EmLenth(xpath)
if undoneCount==0:
print('當前視頻已經完成所有視頻的觀看!')
else:
if ClickEm(xpath=xpath,index=0,scroll=False,sleeptime=3,btnCaption="繼續學習"):
WatchVideo(secHandle)