How to invoke Explicit wait to click on the elemen

2019-08-25 02:33发布

问题:

I am writing the following code to click on the element with text as My Account. It is showing "element not visible". To resolve the issue I am trying expected wait, but it is being timed out. Is there any way around. You can find my code below:

package com.php.travels;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class LogIn {

public static void main(String[] args) {
    System.setProperty(
      "webdriver.chrome.driver", 
      "/Users/owner/desktop/chromedriver");

    WebDriver driver = new ChromeDriver();
    driver.manage().window().maximize();
    driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
    driver.get("https://www.phptravels.net");
    try {
       WebDriverWait wait=new WebDriverWait(driver, 20);

       wait.until(ExpectedConditions.visibilityOfElementLocated(
            By.xpath("//li[@id ='li_myaccount']/a"))
       ).click();

    }
    catch(Throwable t){
        System.out.println("The execption is: " + t);
    }
    finally {
        System.out.println("If no exception tell me now");
    }
}

} // end class

回答1:

To click() on the element with text as My Account instead of visibilityOfElementLocated() you need to induce WebDriverWait through elementToBeClickable() method and you can use the following solution:

  • Code Block:

    System.setProperty("webdriver.gecko.driver", "C:\\Utility\\BrowserDrivers\\geckodriver.exe");
    WebDriver driver=new FirefoxDriver();
    driver.get("http://www.phptravels.net");
    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//nav[@class='navbar navbar-default']//li[@id='li_myaccount']/a[normalize-space()='My Account']"))).click();
    
  • Browser Snapshot: