Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wait iframe page load in Selenium?

I have a page including iframe tags, and want to catch if content is fully loaded in the iframe.

I use time.sleep with check document.readyState and it works well in ideal cases ; strong and fast response from web server. But It seems not to guarantee all situations, and I want to improve my code.

Please tell me know some advice or tips. Thanks.

My envs

  • os : windows 7 x64
  • chrome : 68.0.3440.106 (official, 64bit)
  • python : 3.6.6
  • selenium : 3.14.0

I refer below documents.

  • How to wait a page is loaded in Python Selenium
  • Wait for page load in Selenium
  • Selenium - How to wait until page is completely loaded

and i wrote code below

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)
like image 519
IvoryCirrus Avatar asked Sep 14 '18 07:09

IvoryCirrus


Video Answer


1 Answers

Try below code to wait for iframe and switch to it to be able to handle inner nodes:

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"))

Instead of "iframe_name_or_id" you can pass iframe as WebElement:

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

To wait for presence of element inside frame:

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

You can also use By.NAME, By.CLASS_NAME, By.XPATH, etc...

More about ExplicitWait

like image 155
Andersson Avatar answered Oct 10 '22 18:10

Andersson