简体   繁体   中英

Unable to click on a button present in iframe using selenium webdriver and java

I am trying to click on "Continue" Button of below mentioned URL but nothing is working for me. I have tried click() method, Action class and JavaScriptExecuter but nothing is working. Below is the my code.

System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir")+ "\\src\\main\\resources\\All_Drivers\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://demo.midtrans.com/");
driver.manage().window().maximize();
driver.findElement(By.xpath("//a[@class='btn buy']")).click();
driver.findElement(By.xpath("//div[@class='cart-checkout']")).click();
WebElement frame = driver.findElement(By.id("snap-midtrans"));
driver.switchTo().frame(frame);
WebDriverWait wait = new WebDriverWait(driver,20);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[@class='text-button-main']/span")));
//Continue Button
WebElement elem = driver.findElement(By.xpath("//div[@class='text-button-main']/span"));
Actions action  = new Actions(driver);
action.moveToElement(elem, 561, 526).click().build().perform();
driver.quit();

Any suggestion would be appreciated.

As the the desired element is within an <iframe> so to locate the element you have to:

  • Induce WebDriverWait for the desired frameToBeAvailableAndSwitchToIt() .
  • Induce WebDriverWait for the desired elementToBeClickable() .
  • You can use either of the following Locator Strategies :

    • Using CSS_SELECTOR :

       new WebDriverWait(driver, 10).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.cssSelector("iframe#snap-midtrans"))); new WebDriverWait(driver, 10).until(ExpectedConditions.elementToBeClickable(By.cssSelector("div.text-button-main>span"))).click();
    • Using XPATH :

       new WebDriverWait(driver, 10).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.xpath("//iframe[@id='snap-midtrans']"))); new WebDriverWait(driver, 10).until(ExpectedConditions.elementToBeClickable(By.xpath("//span[text()='Continue']"))).click();

Reference

You can find a coupple of relevant discussions in:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM