WebDriver高阶API(5)

10、UI对象库
定位数据与程序分离

新建一个名叫GoGouTest的工程,工程下新建三个文件,分别为SoGou.py、ObjectMap.py以及UiObjectMap.ini

UiObjectMap.ini 页面元素定位表达式配置文件
[sogou]
searchBox=id>query
searchButton=id=stb

ObjectMap.py 表示ObjexctMap工具类文件,供测试程序调用

#encoding=utf-8
from selenium.webdriver.support.ui import WebDriverWait
import ConfigParser
import os

class ObjectMap(object):
    def __init__(self):
        #获取存放页面元素定位方式及定位表达式的配置文件所在绝对路径
        #os.path.abspath(__file__)表示获取当前文件所在路径目录
        self.uiObjectMapPath = os.path.dirname(os.path.abspath(__file__))+"\\UiObjectMap.ini"
        print self.uiObjectMapPath

    def getElementObject(self,driver,webSiteName,elementName):
        try:
            #创建一个读取配置文件的实例
            cf = ConfigParser.ConfigParser()
            #将配置文件内容加载到内存
            cf.read(self.uiObjectMapPath)
            #根据section和option获取配置文件中页面元素的定位方式及定位表达式组成的字符串,并用">"分割
            locators = cf.get(webSiteName,elementName).split(">")
            #得到定位方式
            locatorMethod = locators[0]
            #得到定位表达式
            locatorExpression = locators[1]
            print locatorMethod,locatorExpression
            #通过显式等待方式 获取页面元素
            element = WebDriverWait(driver,10).until(lambda x: x.find_element(locatorMethod,locatorExpression))
        except Exception,e:
            raise e
        else:
            #当页面元素被找到后,将该页面元素对象返回给调用者
            return element

SoGou.py中调用ObjectMap.py工具类实现测试逻辑

#encoding=utf-8
from selenium import webdriver
import unittest
import time,traceback
from ObjectMap import ObjectMap

class TestSoGouByObjectMap(unittest.TestCase):

    def setUp(self):
        self.obj = ObjectMap()
        #启动浏览器
        self.driver = webdriver.Ie(executable_path="D:\\IEDriverServer")

    def test_SoGouSearch(self):
        url = "http://www.sogou.com"
        #访问搜狗首页
        self.driver.get(url)
        try:
            #查找页面输入框
            searchBox = self.obj.getElementObject(self.driver,"sogou","searchBox")
            #在找到的搜索框中输入关键字
            searchBox.send_keys("World of Warcraft")
            #查找搜索按钮
            searchButton = self.obj.getElementObject(self.driver,"sogou","searchButton")
            #单击找到的搜索按钮
            searchButton.click()
            #等待2秒,以便页面加载完成
            time.sleep(2)
            #断言
            self.assertTrue("World of Warcraft" in self.driver.page_source,"assertError!!!")
        except Exception,e:
            print traceback.print_exc()

    def tearDown(self):
        self.driver.quit()

if __name__ == "__main__":
    unittest.main()

11、精确比较页面截图图片
安装pillow,命令行输入pip install pillow
命令行进行Python交互模块,执行 from PIL import Image没有报错则安装成功

#encoding=utf-8
import unittest,time
from selenium import webdriver
from PIL import Image

class ImageCompare(object):
    """
    本类实现 了对两张图片通过像素比对的算法,获取文件的像素个数大小,然后使用循环的方式将两张
    图片的所有项目进行一一对比,并计算比对结果的相似度的百分比
    """
    def make_regalur_image(self,img,size=(256,256)):
        #将图片尺寸强身重置为指定的size大小
        #然后再将其转换成RGB值
        return img.resize(size).convert("RGB")

    def split_image(self,img,part_size=(64,64)):
        #将图片按给定的大小切分
        w,h = img.size
        pw,ph = part_size
        assert w % pw == h % ph == 0
        return [img.crop((i,j,i+pw,j+ph)).copy() for i in xrange(0,w,pw) for j in xrange(0,h,pw)]

    def hist_similar(self,lh,rh):
        #统计切分后的每部分图片的相似度频率曲线
        assert len(lh) == len(rh)
        return sum(1-(0 if 1 == r else float(abs(1-r))/ max(1,r)) for l,r in zip(lh,rh)) / len(lh)

    def calc_similar(self,li,ri):
        #计算两张图片的相似度
        return sum(self.hist_similar(l.histogram(),r.histogram()) for l,r in zip(self.split_image(li),self.split_image(ri))) / 16.0

    def calc_similar_by_path(self,lf,rf):
        li,ri = self.make_regalur_image(Image.open(lf)),self.make_regalur_image(Image.open(rf))
        return self.calc_similar(li,ri)

class TestDemo(unittest.TestCase):

    def setUp(self):
        self.IC = ImageCompare()
        self.driver = webdriver.Ie(executable_path = "D:\\IEDriverServer")

    def test_ImageComparison(self):
        url = "http://www.sogou.com"
        self.driver.get(url)
        time.sleep(2)
        #截取第一次访问搜狗首页的图片,并保存在本地
        self.driver.save_screenshot("D:\\test\\test\\sogou1.png")
        self.driver.get(url)
        time.sleep(3)
        #截取第二次访问搜首页的图片,并保存在本地
        self.driver.save_screenshot("D:\\test\\test\\sogou2.png")
        #打印两张比对后的相似度,100表示完全匹配
        print self.IC.calc_similar_by_path("D:\\test\\test\\sogou1.png","D:\\test\\test\\sogou2.png") * 100

    def tearDown(self):
        self.driver.quit()

if __name__ == "__main__":
    unittest.main()

 

posted @ 2019-04-02 18:50  测试小子  阅读(194)  评论(0编辑  收藏  举报