如何等待Selenium中的iframe页面加载?

时间:2018-09-14 07:35:55

标签: python unit-testing selenium

我有一个包含iframe标签的页面,并且想要捕获iframe中是否已完全加载内容。

我将time.sleep与检查document.readyState一起使用,在理想情况下效果很好; Web服务器的强大而快速的响应。但这似乎并不能保证所有情况,我想改进自己的代码。

请告诉我一些建议或提示。 谢谢。

我的环境

  • os:Windows 7 x64
  • chrome:68.0.3440.106(官方64位)
  • python:3.6.6
  • 硒:3.14.0

我参考了以下文件。

我在下面写了代码

def wait_for_document(self, driver):
    time.sleep(3)
    for i in range(20):
        if driver.execute_script("return document.readyState") == "complete" : return
        else : time.sleep(1)

3 个答案:

答案 0 :(得分:1)

尝试下面的代码等待iframe并切换到它以能够处理内部节点:

from selenium.webdriver.support import expected_conditions as EC 
from selenium.webdriver.support.ui import WebDriverWait as wait
from selenium.webdriver.common.by import By

driver = webdriver.Chrome() 
driver.get(URL) 
wait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it("iframe_name_or_id"))

您可以将"iframe_name_or_id"作为WebElement来代替iframe

wait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it(driver.find_element_by_xpath('//iframe')))

要等待元素出现在框架中:

wait(driver, 10).until(EC.presence_of_element_located((By.ID, "Element ID")))

您还可以使用By.NAMEBy.CLASS_NAMEBy.XPATH等...

More about ExplicitWait

答案 1 :(得分:0)

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException

browser = webdriver.Chrome('/path/to/driver')
browser.get('http://your/url')
try:
    myElem = WebDriverWait(browser, delay).until(expected_conditions.presence_of_element_located((By.ID, 'id of iframe or whatever')))
except TimeoutException:
    # error

#page is loaded

答案 2 :(得分:0)

you could use this method to  wait for page to fully load:-

public  boolean waitForJStoLoad() {

        WebDriverWait wait = new WebDriverWait(driver, 50);

        JavascriptExecutor js = (JavascriptExecutor) driver;

        ExpectedCondition<Boolean> jQueryLoad = new ExpectedCondition<Boolean>() {
            @Override
            public Boolean apply(WebDriver driver) {
                try {
                    return ((Long)js.executeScript("return jQuery.active") == 0);
                }
                catch (Exception e) {
                    return true;
                }
            }
        };

        // wait for Javascript to load
        ExpectedCondition<Boolean> jsLoad = new ExpectedCondition<Boolean>() {
            @Override
            public Boolean apply(WebDriver driver) {
                return js.executeScript("return document.readyState")
                        .toString().equals("complete");
            }
        };

        return wait.until(jQueryLoad) && wait.until(jsLoad);
    }