E
E
Eugene2019-05-28 12:57:13
Python
Eugene, 2019-05-28 12:57:13

How to wait for a page to fully load in Selenium python?

After the click method, it is not possible to get the tags from the new page, although the transition in Selenium is displayed.

driver = webdriver.Firefox(profile)
 driver.get(url)
driver.find_element_by_xpath("//input[@name='LOGIN']").send_keys(login)
driver.find_element_by_xpath("//input[@name='PASSWORD']").send_keys(password)
driver.find_element_by_xpath("//div[@class='ENTER']/a").click()
new_page = driver.find_element_by_tag_name('html')

While searching for solutions, I found an article that provides two solutions:
class wait_for_page_load(object):
    def __init__(self, browser):
        self.browser = browser
    def __enter__(self):
        self.old_page = self.browser.find_element_by_tag_name('html')
    def page_has_loaded(self):
        new_page = self.browser.find_element_by_tag_name('html')
        return new_page.id != self.old_page.id
    def __exit__(self, *_):
        wait_for(self.page_has_loaded)

with wait_for_page_load(browser):
    browser.find_element_by_link_text('my link').click()

and
from contextlib import contextmanager
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.expected_conditions import staleness_of

class MySeleniumTest(SomeFunctionalTestClass):
    # assumes self.browser is a selenium webdriver

    @contextmanager
    def wait_for_page_load(self, timeout=30):
        old_page = self.browser.find_element_by_tag_name('html')
        yield
        WebDriverWait(self.browser, timeout).until(
            staleness_of(old_page)
        )

    def test_stuff(self):
        # example use
        with self.wait_for_page_load(timeout=10):
            self.browser.find_element_by_link_text('a link')
            # nice!

Unfortunately, I don’t know how to use classes, please help me to embed these classes in my script.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ivan Yakushenko, 2019-05-28
@kshnkvn

from selenium.webdriver.support import expected_conditions as ec

element = WebDriverWait(driver, 10).until(ec.presence_of_element_located((By.TAG_NAME, "html")))

Insert a line with element before the line The code will not continue until the page has loaded.

E
Evgeniy _, 2019-05-29
@GeneD88

You can track the state of the document through document.readyState
When the page is loading, this property will be loading
When the page is loaded - complete
(c) https://www.w3schools.com/jsref/prop_doc_readystate.asp

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question