元素不可交互/元素不可点击

时间:2021-04-12 23:38:58

标签: java selenium selenium-webdriver selenium-chromedriver cucumber

我尝试使用显式等待、ExpectedConditions.elementToBeClickable 和 waitForVisibleElement,但最终超时并等待元素可点击。

我也尝试获取不同的定位器(不同的 div)。这是我的代码(以及我尝试过的代码)

public void setSystemInformationSection() throws Exception {

        scrollPageDownBy800();
        
        //wait.until(ExpectedConditions.elementToBeClickable(INVERTERMANUFACTURERDRPDWN));
        //click(INVERTERMANUFACTURERDRPDWN, "INVERTERMANUFACTURERDRPDWN;");
        
        
        //click(INVERTERMANUFACTURERDRPDWN, "INVERTERMANUFACTURERDRPDWN;");
        //waitForVisibleElement(driver, SMACORE1OPTION); click(SMACORE1OPTION,"SMACORE1OPTION");
                

        Boolean wait = new WebDriverWait(driver,20).until(ExpectedConditions.invisibilityOfElementLocated(By.xpath("//*[@id=\"SMA - Core1\"]")));
        jse.executeScript("arguments[0].click()", INVERTERMANUFACTURERDRPDWN);
        //waitForVisibleElement(driver, SMACORE1OPTION);
        jse.executeScript("arguments[0].click()", SMACORE1OPTION);
}
        

我尝试过的其他下拉菜单与最后一段代码(未注释掉的)一起工作得很好

我用不同的下拉菜单尝试了这个,它工作正常

    public void setCommercialDealType() throws Exception {
        Boolean wait = new WebDriverWait(driver, 20).until(ExpectedConditions.invisibilityOfElementLocated(By.xpath("/html/body/app-root/ng-component/commercial-create-account/main/section[2]/opportunity-information/form/div[2]/div[1]/sp-dropdown/div/div/div[2]/ul/li[2]")));
        jse.executeScript("arguments[0].click()", COMMERCIALDEALTYPEDROPDOWN);
        waitForVisibleElement(driver, COMMERCIALHELIXPPA);
        jse.executeScript("arguments[0].click()", COMMERCIALHELIXPPA);
    }

当我尝试检查 isEnabled 或 isDisplayed 时,它给出了超时错误。我被卡住了。

1 个答案:

答案 0 :(得分:1)

有时一个元素对你来说是可见的或可点击的,但是从 Selenium 的角度来看,div 或 span(或其他元素)会隐藏它。 为了克服这个:

  1. 首先,您通过 ID、xpath 或 Css 表达式查找元素。
  2. 尝试使用 Selenium 移动到该元素(专注于它),然后单击它。
  3. 如果第 2 步失败 - 只需执行 element.click
  4. 如果第 3 步失败 - 使用 javaScript 进行硬点击:

代码示例:

 public void clickLastFoundElement() {        
    try {
        Actions builder = new Actions(browser);
        builder.moveToElement(lastFoundElement).click().build().perform();
    } catch (ElementNotInteractableException x1) {
        try {
            lastFoundElement.click();
        }
        catch (Exception x2) {
            hardClickElement();
        }
    }
}

private void hardClickElement() {
    JavascriptExecutor executor = (JavascriptExecutor) browser;
    executor.executeScript("arguments[0].click();", lastFoundElement);      
}