Selenium 異常錯誤 - 元素在 (x,y) 點不可點選。其他元素將接收點選事件


在使用 Selenium webdriver 時,我們可能會遇到 Selenium 異常錯誤 - 元素在點 (x,y) 處不可點選。其他元素將接收點選事件。

這通常在從 Chrome 瀏覽器執行 Selenium 測試時看到,而在其他瀏覽器(如 IE 和 Firefox)中則不會。發生這種情況是因為 Chrome 瀏覽器無法計算出 web 元素的正確位置。

此外,在 Chrome 瀏覽器中,元素在其中間位置被點選。由於應用程式和 Selenium 之間發生的同步問題,也可能遇到此異常。

有一些解決此問題的方案,如下所列:

  • 我們應該確保我們使用的是最新版本的 chromedriver,並且它與我們本地系統中 Chrome 瀏覽器的版本相容。

  • 獲取 web 元素的座標,然後使用 Actions 類中的方法在其上執行點選操作。

語法

WebElement elm = driver.findElement(By.tagName("input"));
//instance of Point class
Point location = elm.getLocation();
//get x, y coordinates
int m = location.getX();
int n = location.getY();
//instance of Actions class
Actions a = new Actions(driver);
a.moveToElement(elm,m,n).click().build().perform();
  • 使用 JavaScript 執行器獲取 web 元素的座標並點選它。

獲取 x 座標的語法:

WebElement l = driver.findElement(By.tagName("input"));
JavascriptExecutor j =(JavascriptExecutor)driver;
j.executeScript(
   "window.scrollTo(0,"l.getLocation().x+")");
l.click();

獲取 y 座標的語法:

WebElement l = driver.findElement(By.tagName("input"));
JavascriptExecutor j =(JavascriptExecutor)driver;
"window.scrollTo(0,"l.getLocation().y+")");
l.click();

更新於: 2021年6月29日

1K+ 閱讀量

啟動你的 職業生涯

透過完成課程獲得認證

開始學習
廣告