1

A similar question was asked on another thread

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

browser = webdriver.Firefox()
element = WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.ID, "element_id"))

This answer doesn't work because the element already existed in the previous page. I want to be able to wait until the page is done loading and then grab the element.

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
A. Feng
  • 25
  • 1
  • 4
  • can you find another element on the new page and wait for it? – supputuri Mar 12 '19 at 23:30
  • Does it help if you do a `browser.refresh()` immediately after loading the page? – C. Peck Mar 12 '19 at 23:49
  • If the only problem is that the element was found on a page already you could take the easy way out and simply declare the WebElement as a different variable on each page... – C. Peck Mar 13 '19 at 00:19
  • @A.Feng I have edited out the question heading to reflect your usecase. Feel free to revert back the changes if the edit is incorrect. – undetected Selenium Mar 13 '19 at 09:15

2 Answers2

1

As the element existed in the previous page and now you want to grab the element after the page is done loading you can induce WebDriverWait initially for the staleness_of(element) then once again for the element_to_be_clickable(locator) and you can use the following solution:

WebDriverWait(browser, 10).until(EC.staleness_of(driver.find_element_by_id("element_id"))
element = WebDriverWait(browser, 10).until(EC.element_to_be_clickable((By.ID, "element_id"))
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
  • This is not how you use `staleness_of()`. Your method will introduce a race condition based on whether you find the element before or after the page reloads. You need to find the element and store it in `e`, do the action that causes the page to refresh, and THEN wait for staleness of `e`. – JeffC Mar 13 '19 at 18:41
  • What? How have I lost the rights to ask questions on SO? I just figure out my own answers instead of asking others. – JeffC Mar 13 '19 at 18:51
  • ... but none of this has anything to do with why this answer is wrong. I already explained why in my comment... you have no evidence to disprove what I said? – JeffC Mar 13 '19 at 18:51
-1

You can use javascriptexecutor if you want to wait for page to load and then execute further steps.This will return "complete" only if the page is loaded completely.

driver.execute_script("return document.readyState")=="complete"
Sarthak Gupta
  • 392
  • 1
  • 10
  • Selenium already does this by default.... it blocks on page load until readyState = complete. – JeffC Mar 13 '19 at 18:41