简体   繁体   中英

How to wait for iframe contents to load using Selenium WebDriver or JS?

I'm trying to wait for the contents of an iFrame to load but I'm unable to do so without using Thread.sleep().

Do you guys have an idea on how to do this?

Here's my Java code:

   driver.switchTo().frame(driver.findElement(By.cssSelector("iframe.f-iframe")));
//Thread.sleep(3000);

    WebDriverWait wait = new WebDriverWait(driver, 5);
    wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.cssSelector("iframe.f-iframe")));

    String source = driver.getPageSource();
    System.out.println(source); //prints an empty iframe at this point

    waitForElementVisibility(driver, link, 5); //waits using fluent wait for the element
    link.click();
    driver.switchTo().defaultContent();

If I uncomment the Thread.sleep() and comment out all of the waits it works fine.

Web page code:

<html><body><iframe class="f-iframe x-item"><html><body>...</body></html></iframe</body></html>

Can you try this code and see if it works for you?

string iFrameLocator = "iframe.f-iframe"
string linkLocator = "//a[contains(text(),'Link Text')]"

driver.switchTo().frame(driver.findElement(By.cssSelector(iFrameLocator)));

WebDriverWait wait = new WebDriverWait(driver, 5);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(linkLocator)));

String source = driver.getPageSource();
System.out.println(source);

WebElement link = driver.findElement(By.xpath(linkLocator))
link.click();

driver.switchTo().defaultContent();

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