python Selenium own common functions

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 ( 'scroll to {' + btnCaption + str (index + 1) + ' ] failed') 

    the try: 
      dr.execute_script ( "arguments [0] .click ();", BTN) 
      print ( 'click' + btnCaption + '] [' + str (index + 1 ) + '] success') 
      the time.sleep (sleeptime) 
      return True 
    the except: 
      Print ( 'click' + btnCaption + str (index + 1) + ' ] failure') 
      False return 
  the except: 
    Print ( 'targeting' + btnCaption + str (index + 1) + ' failure') 
    return False 

DEF the Login (): 
  u_xpath = 'INPUT // [@ ID = ""]' 
  IF EmKeytext (u_xpath, the USER ): 
    Print ( 'enter a username') 
    p_xpath = 'iNPUT // [@ ID = ""]' 
    IF EmKeytext (p_xpath, the PSWD):
      print ( 'password') 
      v_xpath = 'INPUT // [@ ID = ""]'
      EmKeytext IF (v_xpath): 
        Print ( 'Empty codes') 
        f_xpath =' // "] ' 
        Print (' Enter codes within 20 seconds, and log ') 
        IF EmPresence (f_xpath, 20 is): 
          Print (' successful login ') 
          return True 
  Print (' login failed ') 
  return False 

DEF SwithNewPage (): 
  Handles = dr.window_handles 
  newPage = dr.window_handles [len (Handles) -1] 
  the try: 
    dr.switch_to_window (newPage) 
    Print (' successful handover window ') 
    return True 
  the except: 
    Print (' failure switching window ') 
    return False 

# decorators for decorative: function need to open a new window and return to the original window 
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)
    undoCount the while> 0: 
      ClickEm (= XPath XPath, index = 0, = False Scroll, sleeptime, =. 3, btnCaption = "viewing a video") 

      XPath = '// div [@ class = "Prism-Big-Play- BTN "] 
      ClickEm (= XPath XPath, index = 0, = False Scroll, sleeptime, =. 3, btnCaption =" large button play ") 
      counter = 0 
      the while CheckVideo () == False: 
        counter = counter +. 1 
        IF counter == 600 : 
          BREAK 
        the time.sleep (5) 

      undoCount = EmLenth (xpath) 


DEF CheckVideo (): # processed for problems arising in the course of watching video 
    isDone = False 
    the try: 
        xpath = '// span / span [text () = "has complete "] ' 
        pre = EmPresence (XPath) 
        IF pre: 
          return True 
    the except:
        False return 

DEF LoopStudyVideo (): # into the course, the cycle all courses, watch videos 
  xpath = '// td [@ class = "mycourse-row-operate"] / a [contains (text (), " into the program") or contains (text (), "start learning")] ' 
  courseCount = EmLenth (xpath) 
  mainHandle = dr.current_window_handle # reserved window handle 
  for the X-in the Range (courseCount): 
    ClickEm (xpath xpath =, = the X-index, the Scroll = False, sleeptime = 3, btnCaption = "enter courses or start learning") # Note here that need to watch the video index increment, because there still appear for the exam to learn 
    StudyVideo (mainHandle) 

DEF LoopHomework (): 
  xpath = '// td [@ = class "mycourse-Row-Operate"] / A [the contains (text (), "") or the contains (text (), "")] ' 
  courseCount = EmLenth (XPath) 
  mainHandle = reserved # dr.current_window_handle window handle 
  for x in range (courseCount):
    ClickEm (xpath = xpath, index = 0, scroll = False, sleeptime = 3, btnCaption = " enter courses or start learning") # 0 has been noted here INdex, because the return after the end of the test, the course has been completed. index changes 
    #TryHomework (mainHandle) 
    FinishHomework (mainHandle) 



@SwithTab 
DEF StudyVideo (mainHandle): 
  XPath = '// A [@ class = "Intro-Course-BTN-Intro-Course Button BTN-enable-footer" and the contains (text (), "")] ' 
  DURATION = 10 
  IF EmPresence (XPath): 
    XPath =' // Li / A / span [the contains (text (), "No")] ' 
    undoneCount = EmLenth (XPath) 
    IF undoneCount 0 ==: 
      Print ( 'the current video has finished watching all the videos!') 
    the else: 
      IF ClickEm (= xpath xpath, index = 0, the Scroll = False, sleeptime = 3, btnCaption = "continuous learning"):

  

Guess you like

Origin www.cnblogs.com/nextseven/p/11839518.html