1

I am trying get innerHeight, scrollHeight and scrollTop of a new page after user click the url,

driver.switch_to_window(driver.window_handles[-1]) # switch to newest window after user click some link
WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.TAG_NAME, 'body')))

documentElement = driver.execute_script("return document.documentElement.scrollTop")
innerHeight = driver.execute_script("return window.innerHeight")
pageHeight = driver.execute_script("return document.body.scrollHeight")

However, These script return wrong value because it executed before the new page is completely loaded. How can I get the correct values?

1
  • 1
    You can inspect the document's ready state using JavaScript. driver.execute_script('return document.readyState') Commented Mar 15, 2018 at 4:24

2 Answers 2

3

You can inspect the document's ready state using JavaScript.

state = driver.execute_script('return document.readyState')
if state == 'complete':
    # the page is completely loaded

You can create your own custom expected condition that tests for this.

class document_complete(object):   
    def __call__(self, driver):
        script = 'return document.readyState'
        try:
            return driver.execute_script(script) == 'complete'
        except WebDriverException:
            return False

And use it like any other EC

WebDriverWait(driver, 20).until(document_complete())
Sign up to request clarification or add additional context in comments.

Comments

0

As you are using driver.execute_script, you return your innerHeight, scrollHeight and scrollTop after document.onload or window.onload.

driver.execute_script(document.onload = function(){return document.documentElement.scrollTop})

window.onload is recommended.

Also you can try

driver.execute_script(window.onload=document.documentElement.scrollTop)

2 Comments

it return None after executed this script
Ah I see it, simply please try window.onload=document.documentElement.scrollTop inside execute script

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.