How to properly use .readyState in selenium-python to wait for a web page to be “complete”? [duplicate]

时光毁灭记忆、已成空白 提交于 2020-06-17 15:21:19

问题


I'm trying to get selenium to wait for a page to fully load using .readyState but I can't find the correct way to get selenium to test the .readyState of the web page before proceeding.

The two hashed out lines are my best attempts to get it to work including the example from the link below; in which ".equals" doesn't seem to have any effect.

Is there a way with python-selenium to wait until all elements of a page has loaded?

When running the code with either hashed out line, the output will print "loading" and raise an error because the element postceding the print function is not yet loaded.

note: this problem can easily be solved using waits and Expected Conditions but the question is about using .readyState.

ps: my understanding is that when pageLoadStrategy is set to "normal" then selenium defaults to waiting until .readyState is "complete" however pageLoadStrategy can't be switched between "none" and "normal" once the driver is initiated. If anyone knows otherwise then this could be a possible solution.

from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

caps = DesiredCapabilities().CHROME.copy()
caps["pageLoadStrategy"] = "none"

driver = webdriver.Chrome(
    desired_capabilities=caps,
    executable_path=r'C:\chromedriver_win32\chromedriver.exe'
    )

driver.get("https://www.google.com/maps")
# driver.execute_script("return document.readyState").equals("complete"))
# driver.execute_script("return document.readyState == 'complete'")

print(driver.execute_script("return document.readyState"))
driver.find_element_by_xpath('//*[@id="searchboxinput"]').send_keys("somewhere")

回答1:


You need to use Explicit Wait and read readyState property value, something like:

WebDriverWait(driver, 10).until(lambda driver: driver.execute_script('return document.readyState') == 'complete')

you will also need the following import:

from selenium.webdriver.support.ui import WebDriverWait

More information: How to use Selenium to test web applications using AJAX technology



来源:https://stackoverflow.com/questions/56644956/how-to-properly-use-readystate-in-selenium-python-to-wait-for-a-web-page-to-be

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!