canvas 是一個畫布,定位元素時只能定位到畫布上,如下乳所示,網頁上有一張類似於下圖的eChart報表圖片。selenium的基本定位方式只能定位到該畫布上,畫布上的子元素通過selenium的基礎定位方式是定位不到的, 此時就需要使用selenium的js注入的方式,通過插入js腳本的方式獲取索要操作的元素坐標。 再使用action對應的方法去執行對應的操作。
1: 創建注入js方法。用於獲取canvas畫布上的具體元素消息
window.T={
getCanvasId:function (id){
var cache = *****.echartCache;
var instances = [];
for (var key in cache){
//alert(key);
if (key.indexOf(id) != -1){
instances.push(key);
}
}
return instances
}
}
2: 通過如下js.executeScript方法將js腳本注入頁面。
String jsCode=getText("e:/jsb.js");
Object a=js.executeScript(jsCode);
3: 通過再次注入js腳本的方式調用剛剛注入的js方法,獲取元素在canvas上的元素坐標。
String script = "return window.T.getCanvasId(\"" + keys + "\")";
Object object = js.executeScript(script);
logger.info(object);
static String getText(String path) {
File file=new File(path);
String out=null;
StringBuilder result=new StringBuilder();
try{
BufferedReader br = new BufferedReader(new FileReader(file));//構造一個BufferedReader類來讀取文件
String s = null;
while((s = br.readLine())!=null){//使用readLine方法,一次讀一行
result.append(s+"\n");
}
br.close();
}catch(Exception e){
e.printStackTrace();
}
out=result.toString();
return out;
}
4: 然后,使用action相關方法更具js獲取到的x、y坐標進行操作。
/**
*左鍵點擊元素上的具體坐標位置
* @param driver
* @param abnormElement 需要點擊的元素
* @param x 需要點擊的元素上的點的X坐標
* @param y 需要點擊的元素上的點的Y坐標
*/
public static void mouseClick(WebDriver driver, WebElement abnormElement, int x, int y) {
Actions actions = new Actions(driver);
actions.release();
actions.moveToElement(abnormElement, x, y).click().build().perform();
}
/**
*右鍵點擊元素上的具體坐標位置
* @param driver
* @param abnormElement 需要點擊的元素
* @param x 需要點擊的元素上的點的X坐標
* @param y 需要點擊的元素上的點的Y坐標
*/
public static void mouseRightClick(WebDriver driver, WebElement abnormElement, int x, int y) {
Actions actions = new Actions(driver);
actions.release();
actions.moveToElement(abnormElement, x, y).contextClick().build().perform();
}
/**
*拖拽元素上的具體坐標位置
* @param driver
* @param abnormElement 需要點擊的元素
* @param x 需要點擊的元素上的點的X坐標
* @param y 需要點擊的元素上的點的Y坐標
*/
public static void mouseMoveto(WebDriver driver, WebElement abnormElement, int x, int y){
Actions actions = new Actions(driver);
actions.release();
actions.moveToElement(abnormElement, x, y).clickAndHold().release().build().perform();
}
/**
* 拖拽元素上的具體坐標位置
* @param driver
* @param abnormElement 需要點擊的元素
* @param x 需要拖拽元素點的X坐標
* @param y 需要拖拽元素點的Y坐標
* @param to_x 拖拽元素點目標位置的X坐標
* @param to_y 拖拽元素點目標位置的Y坐標
*/
public static void mouseDragAndDrop(WebDriver driver, WebElement abnormElement, int x, int y,int to_x,int to_y){
Actions actions = new Actions(driver);
actions.release();
actions.moveToElement(abnormElement, x, y).clickAndHold().moveByOffset(to_x,to_y).release().build().perform();
}
————————————————
轉:https://blog.csdn.net/xiaoguanyusb/article/details/80324210