selenium + python自动化测试unittest框架学习(五)webdriver的二次封装

时间:2021-09-18 10:39:44

因为webdriver的api方法很长,再加上大多数的定位方式是以xpath方式定位,更加让代码看起来超级长,为了使整体的代码看起来整洁,对webdriver进行封装,学习资料来源于虫师的《selenium +  python自动化测试》一书。

在与测试用例文件夹同一目录下新建一个文件夹package,用来放置封装方法的模块文件

我们将webdriver二次封装的文件命名为location.py

from selenium import webdriver
from test_case.public import login #login文件中的driver传入 #定位一个元素
def findId(driver,Id):
f = driver.find_element_by_id(Id)
return f def findName(driver,Name):
f = driver.find_element_by_name(Name)
return f def findClassName(driver,ClassName):
f = driver.find_element_by_class_name(ClassName)
return f def findTagName(driver,TagName):
f = driver.find_element_by_tag_name(TagName)
return f def findCss(driver,Css):
f = driver.find_element_by_css_selector(Css)
return f def findLinkText(driver,LinkText):
f = driver.find_element_by_link_text(LinkText)
return f def findPLinkText(driver,PLinkText):
f = driver.find_element_by_partial_Link_text(PLinkText)
return f def findxPath(driver,xPath):
f = driver.find_element_by_xpath(xPath)
return f #定位一组元素 def findsId(driver,Id):
f = driver.find_elements_by_id(Id)
return f def findsName(driver,Name):
f = driver.find_elements_by_name(Name)
return f def findsClassName(driver,ClassName):
f = driver.find_elements_by_class_name(ClassName)
return f def findsTagName(driver,TagName):
f = driver.find_elements_by_tag_name(TagName)
return f def findsCss(driver,Css):
f = driver.find_elements_by_css_selector(Css)
return f def findsLinkText(driver,LinkText):
f = driver.find_elements_by_link_text(LinkText)
return f def findsPLinkText(driver,PLinkText):
f = driver.find_elements_by_partial_link_text(PLinkText)
return f def findsxPath(driver,xPath):
f = driver.find_elements_by_xpath(xPath)
return f

在其他需要用到定位方法的文件中将模块导入,且将文件所在的文件路径加入sys.path路径集中便可引用

#实现webdriver二次封装
from package import location
sys.path.append("D:\\fcj\\study\\seleniumtest\\package")
l = location

之后使用的定位方法则变成以下简洁写法:

例如:find_element_by_id()的方法

l.findId(driver,"id")