混合式自动化测试框架
框架结构:
get地址:https://github.com/zihui1/selenium3-python3
actionb包中的PageAction主要封装常用的元素操作方式
# encoding = utf-8 from selenium import webdriver from util.ObjectMap import getElement from util.WaitUtil import WaitUtil from util.KeyBoardUtil import KeyboardKeys from util.ClipboardUtil import Clipboard from util.DirAndTime import * from config.VarConfig import ieDriverFilePath,chromeDriverFilePath,firefoxDriverFilePath import time # 定义全局driver变量 driver = None # 全局的等待类实例对象 waitUtil = None def open_browser(browserName,*args): global driver,waitUtil try: if browserName.lower() =="ie": driver = webdriver.Ie(executable_path=ieDriverFilePath) elif browserName.lower() =="chrome": driver = webdriver.Chrome() elif browserName.lower() =="firefox": driver = webdriver.Firefox(executable_path=firefoxDriverFilePath) waitUtil = WaitUtil(driver) except Exception as e: raise e def visit_url(url,*args): # 访问某个网址 global driver try: driver.get(url) except Exception as e: raise e def close_browser(*args): # 关闭浏览器 global driver try: driver.quit() except Exception as e: raise e def sleep(sleepSeconds,*args): # 强制等待 try: time.sleep(int(sleepSeconds)) except Exception as e: raise e def clear(locationType,locatorExpression,*args): # 清楚输入框默认内容 global driver try: getElement(driver,locationType,locatorExpression).clear() except Exception as e: raise e def input_string(locationType,locatorExpression,inputContent): # 在输入框中输入内容 global driver try: if inputContent: getElement(driver,locationType,locatorExpression).send_keys(inputContent) except Exception as e: raise e def refresh(*args): # 刷新当前页面 global driver try: driver.refresh() except Exception as e: raise e def click(LocationType,locatorExpression,*args): # 单击页面元素 global driver try: getElement(driver,LocationType,locatorExpression).click() except Exception as e: raise e def Drop_down_box(assertString = None,*args): # 选择ul类型的下拉框 global driver try: if assertString: getElement(driver,"xpath",'//li[text()="'+assertString+'"]').click() except Exception as e: raise e def assert_string_in_pagesource(assertString,*args): # 断言页面源码是否存在关键字或关键字符串 global driver try: assert assertString in driver.page_source,\ u'%s :源码中找不到该关键字!'%(assertString) except AssertionError as e: raise AssertionError(e) except Exception as e: raise e def assert_title(titleStr,*args): # 断言页面标题是否存在给定的关键字符串 global driver try: assert titleStr in driver.title,\ u"%s :title找不到!" %(titleStr) except AssertionError as e: raise AssertionError(e) except Exception as e: raise e def getTitle(*args): # 获取页面标题 global driver try: return driver.title except Exception as e: raise e def getPageSource(*args): # 获取页面源码 global driver try: return driver.page_source except Exception as e: raise e def switch_to_js(locationType,*args): #使用js对页面进行操作 global driver try: return driver.execute_script(locationType) except Exception as e: raise e def switch_to_frame(locationType,frameLocatorExpression,*args): # 切换进入frame global driver try: driver.switch.to.frame(getElement(driver,locationType,frameLocatorExpression)) except Exception as e: print("frame异常") raise e def switch_to_default_content(*args): # 切出frame global driver try: driver.switch_to.default_content() except Exception as e: raise e def paste_string(pasteString,*args): # 模拟键盘复制 try: Clipboard.setText(pasteString) time.sleep(2) KeyboardKeys.twoKeys('ctrl','v') except Exception as e: raise e def press_tab_key(*args): # 模拟键盘tab try: KeyboardKeys.oneKey('tab') except Exception as e: raise e def press_enter_key(*args): # 模拟键盘Enter try: KeyboardKeys.oneKey("enter") except Exception as e: raise e def maximize_browser(): # 窗口最大化 global driver try: driver.maximize_window() except Exception as e: raise e def capture_screen(*args): # 截取屏幕图片 global driver currTime = getCurrentTime() picNameAndPath= str(createCurrentDateDir())+"\\"+str(currTime)+".png" try: driver.get_screenshot_as_file(picNameAndPath.replace('\\',r'\\')) except Exception as e: raise e else: return picNameAndPath def waitPresenceOfElementLocated(locationType,locatorExpression,*args): '''显示等待页面元素出现在Dom中,但并不一定可见,存在则返回该页面元素对象''' global waitUtil try: waitUtil.presenceOfElementLocated(locationType,locatorExpression) except Exception as e: raise e def waitFrameToBeAvailableAndSwitchToIt(locationType,locatorExpression,*args): '''检查frame是否存在,存在则切换进frame控件中''' global waitUtil try: waitUtil.frameToBeAvailaBleSwitchToIt(locationType,locatorExpression) except Exception as e: raise e def waitVisibilityOfElementLocated(locationType,locatorExpression,*args): '''显示等待页面元素出现在DOM中,并且可见,存在返回该页面元素对象''' global waitUtil try: waitUtil.visibilityOfElementLocated(locationType,locatorExpression,*args) except Exception as e: raise e
config包中VarConfig主要放项目路径
# encoding = utf-8 import os # 各浏览器wendriver地址 ieDriverFilePath = "c:\\" chromeDriverFilePath = "c:\\" firefoxDriverFilePath = "c:\\" # 获取当前父级绝对路径 parentDirPath = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) LogPath = parentDirPath+u"\\Log\\" # 异常截图存放目录绝对路径 screePicturesDir = parentDirPath + u'\\exceptionpictures\\' # 存放数据文件存放绝对路径 dataFilePath = parentDirPath+u'\\testData\\登录上海监管平台.xlsx' # 测试数据文件中,测试用例表中部分列对应的数字序号 testCase_testCaseName =2 testCase_frameWorkName = 4 testCase_testStepSheetName =5 testCase_dataSourceSheetName = 6 testCase_isExecute =7 testCase_runTime =8 testCase_testResult = 9 # 用例步骤表中,部分列对应的数字序号 testStep_testStepDescribe = 2 testStep_keyWords = 3 testStep_locationType = 4 testStep_locatorExpression = 5 testStep_operatValue = 6 testStep_runTime = 7 testStep_testResult = 8 testStep_errorInfo = 9 testStep_errorPic = 10 # 数据源表中,是否执行列对应的数字编号 dataSource_isExecute = 13 dataSource_name = 2 dataSource_runTime = 14 dataSource_result = 16
exceptionpictures中主要是放异常截图信息
Log包下放的是Log信息
testData放的是测试用例
testScripts放的是测试脚本
__init__中引入通用的类
#encoding = utf-8 from action.PageAction import * from util.ParseExcel import ParseExcel from config.VarConfig import * from util.Log import Log import time import traceback # 创建解析Excel对象 excelObj = ParseExcel() # 将Excel数据文件加载到内存 excelObj.loadWorkBook(dataFilePath) log = Log()
CreateContacts是数据驱动框架的逻辑
#encoding = utf-8 from . import * from testScripts.WriteTestResult import writeTestResult def dataDriverFun(dataSourceSheetObj,stepSheetObj): try: # 获取数据源表中是否执行列对象 dataIsExecuteColumn = excelObj.getColumn( dataSourceSheetObj,dataSource_isExecute) # 获取数据源表中“姓名”列对象 nameColumn = excelObj.getColumn(dataSourceSheetObj,dataSource_name) # 获取测试步骤表中存在数据区域的行数 stepRowNums = excelObj.getRowsNumber(stepSheetObj) # 记录成功执行的数据条数 successDatas = 0 # 记录被设置为执行的数据条数 requiredDatas = 0 for idx,data in enumerate(dataIsExecuteColumn[1:]): # 遍历数据源表,准备进行数据驱动测试 # 因为第一行是标题行,所以从第二行开始遍历 if data.value == "y": log.info(u'开始添加监管人员%s'%(nameColumn[idx+1].value)) requiredDatas +=1 # 定义记录执行成功步骤数变量 successStep = 0 for index in range(2,stepRowNums+1): # 获取数据驱动测试步骤表中第index行对象 rowObj = excelObj.getRow(stepSheetObj,index) # 获取关键字作为调用的函数名 keyWord = rowObj[testStep_keyWords -1].value # 获取操作元素的定位表达式作为调用函数的参数 locationType = rowObj[testStep_locationType -1].value # 获取操作元素的定位表达式作为调用的函数的参数 locatorExpression = rowObj[testStep_locatorExpression -1].value # 获取操作值作为调用函数的参数 operateValue = rowObj[testStep_operatValue -1].value if isinstance(operateValue,int): operateValue = str(operateValue) if operateValue and operateValue.isalpha(): # 如果operateValue变量不为空,说明有操作值从数据源表中 # 根据坐标获取对应单元格的数据 coordinate = operateValue+str(idx+2) operateValue = excelObj.getCellOfValue(dataSourceSheetObj,\ coordinate=coordinate) if isinstance(operateValue, int): operateValue = str(operateValue) # 构造需要执行的python表达式,此表达式对应的是PageAction.py文件 # 中的页面动作函数调用的字符串表示 tmpStr = "'%s','%s'"%(locationType.lower(),locatorExpression.replace(\ "'",'"'))if locationType and locatorExpression else"" if tmpStr: tmpStr+=\ ",u'"+operateValue+"'" if operateValue else "" else: tmpStr +=\ "u'"+operateValue+"'" if operateValue else "" runStr = keyWord+"("+tmpStr+")" print(runStr) try: eval(runStr) except Exception as e: log.error(u'执行步骤%s发生异常'%rowObj[testStep_testStepDescribe-1].value) log.error(traceback.print_exc()) # # 截取异常屏幕图片 # capturePic = capture_screen() # # 获取详细的异常堆栈信息 # errorInfo = traceback.format_exc() # writeTestResult(stepSheetObj, rowNo=index, \ # colsNo="caseStep", testResult="faild", \ # errorInfo=str(errorInfo), picPath=capturePic) else: successStep+=1 log.info(u'执行步骤%s成功'%rowObj[testStep_testStepDescribe-1].value) if stepRowNums == successStep+1: successDatas+=1 # 如果成功执行的步骤数等于步骤表中给出的步骤数 # 说明第idx+2行的数据执行通过,写入通过信息 writeTestResult(dataSourceSheetObj,rowNo=idx+2,colsNo="dataSheet",\ testResult="pass") else: # 写入失败信息 writeTestResult(dataSourceSheetObj,rowNo=idx+2,colsNo="dataSheet",\ testResult="faild") else: # 将不需要执行的数据行的执行时间和执行结果单元格清空 writeTestResult(dataSourceSheetObj,rowNo=idx+2,colsNo="dataSheet",\ testResult="") if requiredDatas == successDatas: # 只要当成功执行的数据条数等于被设置为需要执行的数据条数, # 才表示调用数据驱动的测试用例执行通过 return 1 # 表示调用数据驱动的测试用例执行失败 return None except Exception as e: raise e
WriteTestResult放入写入测试用例的格式和引入位置信息
#encoding = utf-8 from . import * # 用例或用例步骤执行结束后,向Excel中写执行结果信息 def writeTestResult(sheetObj,rowNo,colsNo,testResult, errorInfo = None,picPath = None): # 测试通过结果信息为绿色,失败为红色 colorDict = {"pass":"green","faild":"read","":None} # 因为“测试用例”工作表和“用例不走Sheet表”中都有测试执行时间和测试 # 结果列,定义此字典对象是为了区分具体应该写那个工作表 colsDict = { "testCase":[testCase_runTime,testCase_testResult], "caseStep":[testStep_runTime,testStep_testResult], "dataSheet":[dataSource_runTime,dataSource_result]} try: # 在测试步骤sheet中,写入测试结果 excelObj.writeCell(sheetObj,content=testResult,\ rowNo=rowNo,colsNo=colsDict[colsNo][1],\ style=colorDict[testResult]) if testResult == "": # 清空时间单元格内容 excelObj.writeCell(sheetObj,content="",\ rowNo= rowNo,colsNo= colsDict[colsNo][0]) else: # 在测试步骤sheet中,写入测试时间 excelObj.writeCellCurrentTime(sheetObj,rowNo=rowNo,colsNo=colsDict[colsNo][0]) if errorInfo and picPath: # 在测试步骤sheet中,写入异常信息 excelObj.writeCell(sheetObj,content=errorInfo,rowNo=rowNo,\ colsNo=testStep_errorInfo) # 在测试步骤sheet中,写入异常截图路径 excelObj.writeCell(sheetObj,content=picPath,rowNo=rowNo,colsNo=testStep_errorPic) else: if colsNo=="caseStep": # 在测试步骤sheet中,清空异常信息单元格 excelObj.writeCell(sheetObj,content="",rowNo=rowNo,colsNo=testStep_errorInfo) excelObj.writeCell(sheetObj,content="",rowNo=rowNo,colsNo=testStep_errorPic) except Exception as e: log.error(u'写excel时发生异常'+traceback.print_exc())
TestShNw放的执行测试步骤
#encoding = utf-8 from . import * from . import CreateContacts from testScripts.WriteTestResult import writeTestResult def TestShNw(): try: # 根据Excel文件中的sheet名获取sheet对象 caseSheet = excelObj.getSheetByName(u'测试用例') # 获取测试用例sheet中是否执行列对象 isExecuteColumn = excelObj.getColumn(caseSheet,testCase_isExecute) # 记录执行成功的测试用例个数 successfulCase = 0 # 记录需要执行的用例个数 requiredCase =0 for idx,i in enumerate(isExecuteColumn[1:]): # 因为用例sheet中第一行为标题行,无须执行 caseName = excelObj.getCellOfValue(caseSheet,rowNo=idx+2,\ colsNo=testCase_testCaseName) # 循环遍历“测试用例”表中的测试用例,执行被设置为执行的用例 if i.value.lower() == "y": requiredCase +=1 # 获取测试用例表中,第idx+1行中 # 用例执行时所使用的框架类型 useFrameWorkName = excelObj.getCellOfValue(\ caseSheet,rowNo=idx+2,colsNo=testCase_frameWorkName) # 获取测试用例列中,第idx+1行中执行用例的步骤sheet名 stepSheetName = excelObj.getCellOfValue(\ caseSheet,rowNo=idx+2,colsNo=testCase_testStepSheetName) log.info('----------'+stepSheetName) if useFrameWorkName == u'数据': log.info(u'***********调用数据驱动************') # 获取测试用例表中,第idx+1行,执行框架为数据驱动的用例所使用的数据sheet名 dataSheetName = excelObj.getCellOfValue(\ caseSheet,rowNo=idx+2,colsNo=testCase_dataSourceSheetName) # 获取第idx+1行测试用例的步骤sheet对象 stepSheetObj = excelObj.getSheetByName(stepSheetName) # 获取第idx+1行测试用例使用的数据sheet对象 dataSheetObj = excelObj.getSheetByName(dataSheetName) # 通过数据驱动框架执行添加联系人 result = CreateContacts.dataDriverFun(dataSheetObj,stepSheetObj) if result: log.info(u'用例%s执行成功'%(caseName)) successfulCase+=1 writeTestResult(caseSheet,rowNo=idx+2,\ colsNo="testCase",testResult="pass") else: log.info(u'用例%s执行失败'%(caseName)) writeTestResult(caseSheet,rowNo=idx+2,colsNo="testCase",testResult="faild") elif useFrameWorkName == u"关键字": log.info("*************调用关键字驱动****************") caseStepObj = excelObj.getSheetByName(stepSheetName) stepNums = excelObj.getRowsNumber(caseStepObj) successfulSteps = 0 log.info(u'测试用例工%s步'%(stepNums)) for index in range(2,stepNums+1): # 因为第一行标题行无须执行 # 获取步骤sheet中第index行对象 stepRow = excelObj.getRow(caseStepObj,index) # 获取关键字作为调用的函数名 keyWord = stepRow[testStep_keyWords -1].value # 获取操作元素定位方式作为调用的函数的参数 locationType = stepRow[testStep_locationType -1].value # 获取操作元素的定位表达式作为调用函数的参数 locatorExpression = stepRow[testStep_locatorExpression -1].value # 获取操作值为调用函数的参数 operateValue = stepRow[testStep_operatValue -1].value if isinstance(operateValue,int): # 如果operateValue值为数字型, # 将其转换为字符串,方便字符串拼接 operateValue = str(operateValue) # 构造需要执行的Python表达式,此表达式对应的是PageAction.py文件 # 中的页面动作函数调用的字符串表达式 tmpStr = "'%s','%s'"%(locationType.lower(),\ locatorExpression.replace("'",'"')\ )if locationType and locatorExpression else "" if tmpStr: tmpStr+=\ ",u'"+operateValue+"'" if operateValue else "" else: tmpStr +=\ "u'"+operateValue+"'" if operateValue else "" runStr = keyWord+"("+tmpStr+")" print(runStr) try: # 通过eval函数,将拼接的页面动作函数调用的字符串表示 # 当成有效的Python表达式执行,从而执行测试步骤的sheet # 中关键字在PageAction.py文件中对应的映射方法, # 来完成对页面元素的操作 eval(runStr) except Exception as e: log.info(u"执行步骤%s发生异常"%(stepRow[testStep_testStepDescribe-1].value)) # 截取异常屏幕图片 capturePic = capture_screen() # 获取详细的异常堆栈信息 errorInfo = traceback.format_exc() writeTestResult(caseStepObj,rowNo=index,\ colsNo="caseStep",testResult="faild",\ errorInfo=str(errorInfo),picPath=capturePic) else: successfulSteps +=1 log.info(u'执行步骤%s成功'%(stepRow[testStep_testStepDescribe-1].value)) writeTestResult(caseStepObj,rowNo=index,colsNo="caseStep",testResult="pass") if successfulSteps == stepNums -1: successfulCase+=1 log.info(u'用例%s执行通过'%(caseName)) writeTestResult(caseSheet,rowNo=idx+2,\ colsNo="testCase",testResult="pass") else: log.info(u"用例%s执行失败"%(caseName)) writeTestResult(caseSheet,rowNo=idx+2,colsNo="testCase",testResult="faild") else: # 清空不需要执行用例的执行时间和执行结果, # 异常信息,异常图片单元格 writeTestResult(caseSheet,rowNo=idx+2,\ colsNo="testCase",testResult="") log.info(u"共%s条用例,%s条需要被执行,成功执行%s条"\ %(len(isExecuteColumn)-1,requiredCase,successfulCase)) except Exception as e: log.info("出现异常"+traceback.format_exc())
util包为工具类包封装一些工具类
DirAndTime是封装截图位置和时间信息
# encoding = utf-8 import time,os from datetime import datetime from config.VarConfig import screePicturesDir # 获取当前日期 def getCurrentDate(): timeTup = time.localtime() currentDate = str(timeTup.tm_year)+"-"+str(timeTup.tm_mon)+"-"+\ str(timeTup.tm_mday) return currentDate # 获取当前时间 def getCurrentTime(): timeStr = datetime.now() nowTime = timeStr.strftime('%H-%M-%S-%f') return nowTime # 创建截图存放目录 def createCurrentDateDir(): dirName = os.path.join(screePicturesDir,getCurrentDate()) if not os.path.exists(dirName): os.makedirs(dirName) return dirName if __name__ == "__main__": print(getCurrentDate()) print(getCurrentTime()) print(createCurrentDateDir())
Log封装Log类
#coding=utf-8 import logging import time from config.VarConfig import * class Log: def __init__(self): self.logname = os.path.join(LogPath, '{0}.log'.format(time.strftime('%Y-%m-%d'))) def __printconsole(self, level, message): # 创建一个logger logger = logging.getLogger() logger.setLevel(logging.DEBUG) # 创建一个handler,用于写入日志文件 fh = logging.FileHandler(self.logname,'a',encoding='utf-8') fh.setLevel(logging.DEBUG) # 再创建一个handler,用于输出到控制台 ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) # 定义handler的输出格式 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') fh.setFormatter(formatter) ch.setFormatter(formatter) # 给logger添加handler logger.addHandler(fh) logger.addHandler(ch) # 记录一条日志 if level == 'info': logger.info(message) elif level == 'debug': logger.debug(message) elif level == 'warning': logger.warning(message) elif level == 'error': logger.error(message) logger.removeHandler(ch) logger.removeHandler(fh) # 关闭打开的文件 fh.close() def debug(self,message): self.__printconsole('debug', message) def info(self,message): self.__printconsole('info', message) def warning(self,message): self.__printconsole('warning', message) def error(self,message): self.__printconsole('error', message) if __name__ == "__main__": Log().info("infisdlfjkdsf")
ObjectMap封装选择器类
# encoding = utf-8 from selenium.webdriver.support.ui import WebDriverWait # 获取单个元素 def getElement(driver,locationType,locatorExpression): try: element = WebDriverWait(driver,30).until(\ lambda x:x.find_element(by=locationType,value=locatorExpression)) return element except Exception as e: raise e # 获取多个相同类型的元素对象已List返回 def getElements(driver,locationType,locatorExpression): try: element = WebDriverWait(driver,30).until(\ lambda x:x.find_elements(by=locationType,value=locatorExpression)) return element except Exception as e: raise e
ParseExcel封装读写Excel类
# encoding = utf-8 import openpyxl from openpyxl.styles import Border,Side,Font import time class ParseExcel(object): def __init__(self): self.worbook = None self.excelFile = None self.font = Font(color = None)#设置字体颜色 # 颜色对应的RGB值 self.RGBDict = {'read':'FFFF3030','green':'FF008B00'} def loadWorkBook(self,excelPathAndName): # 将Excel文件加载到内存,并获取其workbook对象 try: self.workbook = openpyxl.load_workbook(excelPathAndName) except Exception as e: raise e self.excelFile = excelPathAndName return self.workbook def getSheetByName(self,sheetName): # 根据sheet名获取该sheet对象 try: sheet = self.workbook.get_sheet_by_name(sheetName) return sheet except Exception as e: raise e def getSheetByIndex(self,sheetIndex): # 根据sheet的索引号获取该sheet对象 try: sheetName = self.workbook.get_sheet_names()[sheetIndex] except Exception as e: raise e sheet = self.workbook.get_sheet_by_name(sheetName) return sheet def getRowsNumber(self,sheet): # 获取sheet中有数据区域的结束行号 return sheet.max_row def getColsNumber(self,sheet): # 获取sheet中数据区域的结束列号 return sheet.max_column def getStartRowNumber(self,sheet): # 获取sheet中有数据区域的开始的行号 return sheet.min_row def getStartColNumber(self,sheet): # 获取sheet中有数据区域的开始的列号 return sheet.min_column def getRow(self,sheet,rowNo): # 获取sheet中某一行,返回的是这一行所有的数据内容组成的tuple, # 下标从1开始,sheet.rows[1]表示第一列 try: return list(sheet.rows)[rowNo - 1] except Exception as e: raise e def getColumn(self,sheet,colNo): # 获取sheet中某一列,返回的是这一列所有的数据内容组成tuple, # 下标从1开始,sheet.coulumns[1]表示第一列 try: return list(sheet.columns)[colNo -1] except Exception as e: raise e def getCellOfValue(self,sheet,coordinate = None,rowNo = None,colsNo = None): # 根据单元格所在的位置索引获取该单元格中的值,下表从1开始 # sheet.cell(row =1,column = 1).value,表示Excel中第一行第一列的值 if coordinate != None: try: return sheet[coordinate].value except Exception as e: raise e elif coordinate is None and rowNo is not None and rowNo is not None and colsNo is not None: try: return sheet.cell(row = rowNo,column = colsNo).value except Exception as e: raise e else: raise Exception("Insufficient Coordinates of cell!") def getCellOfObject(self,sheet,coordinate = None,rowNo = None,colsNo = None): # 获取某个单元格的对象,可以根据单元格所在位置的数字索引, # 也可以直接根据Excel中单元格的编码及坐标 # 如getCellObject(sheet,coordinate = 'A1')或 # getCellObject(sheet,rowNo = 1,colsNo = 2) if coordinate != None: try: return sheet.cell(coordinate = coordinate) except Exception as e: raise e elif coordinate == None and rowNo is not None and colsNo is not None: try: return sheet.cell(row = rowNo,column = colsNo) except Exception as e: raise e else: raise Exception("Insufficient Coordinates of cell!") def writeCell(self,sheet,content,coordinate = None,rowNo = None,colsNo = None,style = None): # 根据单元格在Excel中的编码坐标或者数字索引坐标向单元格中写入数据, # 下表从1开始,参数style表示字体的颜色的名字,比如red,green if coordinate is not None: try: sheet.cell(coordinate = coordinate).value = content if style is not None: sheet.cell(coordinate = coordinate).\ font = Font(color= self.RGBDict[style]) self.workbook.save(self.excelFile) except Exception as e: raise e elif coordinate == None and rowNo is not None and colsNo is not None: try: sheet.cell(row = rowNo,column = colsNo).value = content if style: sheet.cell(row = rowNo,column = colsNo).\ font = Font(color=self.RGBDict[style]) self.workbook.save(self.excelFile) except Exception as e: raise e else: raise Exception("Insufficient Coordinates of cell!") def writeCellCurrentTime(self,sheet,coordinate = None,rowNo = None,colsNo = None): # 写入当前的时间,下表从1开始 now = int(time.time())#显示为时间戳 timeArray = time.localtime(now) currentTime = time.strftime("%Y-%m-%d %H:%M:%S",timeArray) if coordinate is not None: try: sheet.cell(coordinate = coordinate).value = currentTime self.workbook.save(self.excelFile) except Exception as e: raise e elif coordinate == None and rowNo is not None and colsNo is not None: try: sheet.cell(row = rowNo,column = colsNo).value = currentTime self.workbook.save(self.excelFile) except Exception as e: raise e else: raise Exception("Insufficient Coordinates of cell!") if __name__ == "__main__": from config.VarConfig import * pe = ParseExcel() pe.loadWorkBook(dataFilePath) print('通过名称获取sheet对象的名称:',pe.getSheetByName(u'联系人').title) print('通过索引号获取sheet对象的名称:',pe.getSheetByIndex(0).title) sheet = pe.getSheetByIndex(0) print(type(sheet)) print('获取最大行',pe.getRowsNumber(sheet))#获取最大行 print('获取最大列',pe.getColsNumber(sheet))#获取最大列 rows = pe.getRow(sheet,1)#获取第一行 print(rows().value) for i in rows: print(i.value) print(pe.getCellOfValue(sheet,rowNo=1,colsNo=1)) # pe.writeCell(sheet,u'我爱祖国',rowNo=10,colsNo=10) # pe.writeCellCurrentTime(sheet,rowNo=10,colsNo=11)
WaitUtil封装显示等待元素
# encoding = utf-8 from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC import time class WaitUtil(object): def __init__(self,driver): self.locationTypeDict = { "xpath":By.XPATH, "id":By.ID, "name":By.NAME, "class_name":By.CLASS_NAME, "tag_name":By.TAG_NAME, "like_text":By.LINK_TEXT, "partial_link_text":By.PARTIAL_LINK_TEXT } self.driver = driver self.wait = WebDriverWait(self.driver,30) def presenceOfElementLocated(self,locationType,locatorExpression,*args): '''显示等待页面元素出现在Dom中,但并不一定可见,存在则返回该页面元素对象''' try: if locationType.lower() in self.locationTypeDict: element = self.wait.until(EC.presence_of_element_located((self.locationTypeDict[\ locationType.lower()],locatorExpression))) return element else: raise TypeError(u"未找到定位方式,请确认定位方法是否写正确") except Exception as e: raise e def frameToBeAvailaBleSwitchToIt(self,locationType,locatorExpression,*args): ''' 检查Frame是否存在,存在则切换斤Frame控件中 ''' try: self.wait.until(EC.frame_to_be_available_and_switch_to_it((self.locationTypeDict[\ locationType.lower()],locatorExpression))) except Exception as e: raise e def visibilityOfElementLocated(self,locationType,locatorExpression,*args): '''显示等待页面元素出现''' try: element = self.wait.until(EC.visibility_of_element_located((\ self.locationTypeDict[locationType.lower()],locatorExpression))) return element except Exception as e: raise e if __name__ == "__main__": from selenium import webdriver driver = webdriver.Chrome() driver.get("http://mail.163.com") wu = WaitUtil(driver) wu.frameToBeAvailaBleSwitchToIt("xpath","//iframe[starts-with(@id, 'x-URS-iframe')]") ps = wu.visibilityOfElementLocated("name","email") wc = wu.presenceOfElementLocated("name","email") # wc = WebDriverWait(driver, 30).until(EC.presence_of_element_located((By.NAME, 'email'))) wc.send_keys("1111") ps.send_keys("11111") time.sleep(5) driver.quit()