zoukankan      html  css  js  c++  java
  • python Selenium自己常用的函数

    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)+'
    ')
        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)
    

      

  • 相关阅读:
    制作windows服务
    DTCMS部署错误
    mysql常用操作
    eclipse maven jdk全局设置
    linux下安装lnmp环境
    aliyun阿里云Maven仓库地址——加速你的maven构建
    移动端前端框架UI库(Frozen UI、WeUI、SUI Mobile)
    getFields和getDeclaredFields
    2016暑假集训第三次训练赛题解
    HDU5863 cjj's string game(DP + 矩阵快速幂)
  • 原文地址:https://www.cnblogs.com/nextseven/p/11839518.html
Copyright © 2011-2022 走看看