Check if element is clickable in Selenium Java

前端 未结 7 2028
南旧
南旧 2020-11-29 08:19

I\'m new to Selenium and need to check if element is clickable in Selenium Java, since element.click() passes both on

7条回答
  •  爱一瞬间的悲伤
    2020-11-29 08:57

    There are certain things you have to take care:

    • WebDriverWait inconjunction with ExpectedConditions as elementToBeClickable() returns the WebElement once it is located and clickable i.e. visible and enabled.
    • In this process, WebDriverWait will ignore instances of NotFoundException that are encountered by default in the until condition.
    • Once the duration of the wait expires on the desired element not being located and clickable, will throw a timeout exception.
    • The different approach to address this issue are:
      • To invoke click() as soon as the element is returned, you can use:

        new WebDriverWait(driver, 10).until(ExpectedConditions.elementToBeClickable(By.xpath("(//div[@id='brandSlider']/div[1]/div/div/div/img)[50]"))).click();
        
      • To simply validate if the element is located and clickable, wrap up the WebDriverWait in a try-catch{} block as follows:

        try {
               new WebDriverWait(driver, 10).until(ExpectedConditions.elementToBeClickable(By.xpath("(//div[@id='brandSlider']/div[1]/div/div/div/img)[50]")));
               System.out.println("Element is clickable");
             }
        catch(TimeoutException e) {
               System.out.println("Element isn't clickable");
            }
        
      • If WebDriverWait returns the located and clickable element but the element is still not clickable, you need to invoke executeScript() method as follows:

        WebElement element = new WebDriverWait(driver, 10).until(ExpectedConditions.elementToBeClickable(By.xpath("(//div[@id='brandSlider']/div[1]/div/div/div/img)[50]"))); 
        ((JavascriptExecutor)driver).executeScript("arguments[0].click();", element);
        

提交回复
热议问题