因为webdriver的api方法很长,再加上大多数的定位方式是以xpath方式定位,更加让代码看起来超级长,为了使整体的代码看起来整洁,对webdriver进行封装,学习资料来源于虫师的《selenium + python自动化测试》一书。
在与测试用例文件夹同一目录下新建一个文件夹package,用来放置封装方法的模块文件
我们将webdriver二次封装的文件命名为location.py
from selenium import webdriverfrom test_case.public import login #login文件中的driver传入#定位一个元素def findId(driver,Id): f = driver.find_element_by_id(Id) return fdef findName(driver,Name): f = driver.find_element_by_name(Name) return fdef findClassName(driver,ClassName): f = driver.find_element_by_class_name(ClassName) return fdef findTagName(driver,TagName): f = driver.find_element_by_tag_name(TagName) return fdef findCss(driver,Css): f = driver.find_element_by_css_selector(Css) return fdef findLinkText(driver,LinkText): f = driver.find_element_by_link_text(LinkText) return fdef findPLinkText(driver,PLinkText): f = driver.find_element_by_partial_Link_text(PLinkText) return fdef findxPath(driver,xPath): f = driver.find_element_by_xpath(xPath) return f#定位一组元素def findsId(driver,Id): f = driver.find_elements_by_id(Id) return fdef findsName(driver,Name): f = driver.find_elements_by_name(Name) return fdef findsClassName(driver,ClassName): f = driver.find_elements_by_class_name(ClassName) return fdef findsTagName(driver,TagName): f = driver.find_elements_by_tag_name(TagName) return fdef findsCss(driver,Css): f = driver.find_elements_by_css_selector(Css) return fdef findsLinkText(driver,LinkText): f = driver.find_elements_by_link_text(LinkText) return fdef findsPLinkText(driver,PLinkText): f = driver.find_elements_by_partial_link_text(PLinkText) return fdef findsxPath(driver,xPath): f = driver.find_elements_by_xpath(xPath) return f
在其他需要用到定位方法的文件中将模块导入,且将文件所在的文件路径加入sys.path路径集中便可引用
#实现webdriver二次封装from package import locationsys.path.append("D:\\fcj\\study\\seleniumtest\\package")l = location
之后使用的定位方法则变成以下简洁写法:
例如:find_element_by_id()的方法
l.findId(driver,"id")