Selenium2学习-030-WebUI自动化实战实例-028-获取元素位置及大小

时间:2021-05-26 16:37:25

自动化测试过程中,有时需要获取元素的位置、大小,以获取元素的位置,通过 Actions 模拟鼠标,进行相对坐标操作。例如,有些元素定位不方便,或者需要对某一元素相对区域范围进行暴力点击测试,此时就需要获取相应的坐标。

获取元素位置和大小的源码比较简单,直接上码了......敬请参阅!

     /**
* Get element position, and return integer Array [left, top, width, height]
*
* @author Aaron.ffp
* @version V1.0.0: autoSeleniumDemo main.aaron.sele.core SeleniumCore.java getElementPositionAndSize, 2015-7-27 23:38:31 Exp $
*
* @param webdriver : WebDriver
* @param by : By
*
* @return int[left,top,width,height]
*/
public int[] getElementPositionAndSize(WebDriver webdriver, By by){
// store element position
int[] elementPosition = new int[4]; // get element
WebElement element = webdriver.findElement(by); // get location of element
Point e_location = element.getLocation(); // get size of element
Dimension e_size = element.getSize(); elementPosition[0] = e_location.getX();
elementPosition[1] = e_location.getY();
elementPosition[2] = e_size.width;
elementPosition[3] = e_size.height; return elementPosition;
} /**
* Get element position, and return integer Array [left, top, width, height]
*
* @author Aaron.ffp
* @version V1.0.0: autoSeleniumDemo main.aaron.sele.core SeleniumCore.java getElementPositionAndSize, 2015-7-27 23:35:31 Exp $
*
* @param by : By
*
* @return int[left,top,width,height]
*/
public int[] getElementPositionAndSize(By by){
// store element position
int[] elementPosition = new int[4]; // get element
WebElement element = this.webdriver.findElement(by); // get location of element
Point e_location = element.getLocation(); // get size of element
Dimension e_size = element.getSize(); elementPosition[0] = e_location.getX();
elementPosition[1] = e_location.getY();
elementPosition[2] = e_size.width;
elementPosition[3] = e_size.height; return elementPosition;
}

至此,WebUI 自动化功能测试脚本第 028-获取元素位置及大小 顺利完结,希望此文能够给初学 Selenium 的您一份参考。

最后,非常感谢亲的驻足,希望此文能对亲有所帮助。热烈欢迎亲一起探讨,共同进步。非常感谢! ^_^