Selenium:元素在点上不可点击

时间:2016-05-23 10:42:57

标签: java selenium

此问题是由于chrome driver始终clicks element的中间部分,试图忠实于实际用户所做的事情。 所以我在考虑这种方法:

首先,而不是找到一个元素,然后单击:

driver.fineElement(By.xpath("bla bla")).click()

编写点击WebElement的通用函数:

def clickOnWebElement(WebElement webElement) {
 int counter = 0;
 boolean isClicked = false;

 Thread.sleep(1000);
try {
    while (count < 2 && !isClicked) {

     if (count == 0) {
        webElement.click()
        isClicked = true;
     }     
     else if (count == 1) {
        Actions action = new Actions(driver);
        action.moveToElement(webElement).click().perform();
        isClicked = true;
       }
     else if (count == 2) {
        JavascriptExecutor js =(JavascriptExecutor)driver;
       js.executeScript("window.scrollTo(0,"element.getLocation().x+")");
        webElement.click();
        isClicked = true;
       }
    }
  }
catch(Exception ex) {
    count++;
    Thread.sleep(2000);
  }
}

然后当发生此异常时,请尝试不同的方式进行点击。

您认为这种方法可行吗?

1 个答案:

答案 0 :(得分:1)

请仔细阅读this堆栈溢出答案,以便更好地理解。

更新我们也可以尝试

There are many Conditions that we can use withing Webdriver tests.

1. visibilityOf(WebElement element) : An expectation for checking that an element, known 
to be present on the DOM of a page, is visible.
2. visibilityOfElementLocated(By locator) : An expectation for checking that an element 
is present on the DOM of a page and visible.

In the above two conditions we are waiting for an element to be present on the DOM 
of a page and also visible. These works fine only when the element is loaded completely.

另请尝试如下

尝试使用Y坐标

单击
WebElement elementToClick = driver.findElement(By.xpath("Your xpath"));
// Scroll the browser to the element's Y position
((JavascriptExecutor)driver).executeScript("window.scrollTo(0,"+elementToClick.getLocation().y+")");
// Click the element
elementToClick.click();

尝试使用X坐标

单击
WebElement elementToClick = driver.findElement(By.xpath("Your xpath"));
// Scroll the browser to the element's X position
((JavascriptExecutor)driver).executeScript("window.scrollTo(0,"+elementToClick.getLocation().x+")");
// Click the element
elementToClick.click();

希望这有助于你