How to determine if a page is loaded using selenium?

时间秒杀一切 提交于 2021-02-19 07:07:23

问题


I am interacting with a database that returns the newspaper reports about a event using selenium. Every time I implement a search query, the database opens a new page and starts to load all newspaper reports about the event. The webpage has an element that reports the total number of relevant reports found. The number changes before the page is fully loaded.

My question is there a way to determine if the page is loaded. My current strategy is to check the number of total reports in a loop and decides the page is complete when two loops report the same number of total reports. I am not sure if this is a good strategy.


回答1:


My current strategy is to check the number of total reports in a loop and decides the page is complete when two loops report the same number of total reports. I am not sure if this is a good strategy.

It is.

There is no universal rule when "a page is loaded" in a sense that you can interact with it in an expected way and be able to control the desired elements. Checking the counter - how much results are loaded is a common condition to use for a "wait" - usually an Explicit Wait.

The results counter is especially commonly used when there is an "infinite" scroll pagination on a page - every time we scroll we check that the current results count became greater than when the before the scroll - this is an indication that a new portion of results arrived and we can scroll again.




回答2:


As you are interacting with a database (possibly a Button or a Link) the database opens a new page and starts to load all newspaper reports about the event, so evaluting ("return document.readyState").equals("complete") won't help us here.

As per your question statement :

My current strategy is to check the number of total reports in a loop and decides the page is complete when two loops report the same number of total reports.

Yes that is the exact way but you haven't thrown any light on how you implemented the solution.

The most effective solution would be to induce WebDriverWait with expected_conditions clause set to either of the following :

  • text_to_be_present_in_element(locator, text_) :

    WebDriverWait(driver, 10).until(EC.text_to_be_present_in_element((By.CSS_SELECTOR, "css_selector"), "2"))
    
  • text_to_be_present_in_element_value(locator, text_) :

    WebDriverWait(driver, 10).until(EC.text_to_be_present_in_element_value((By.CSS_SELECTOR, "css_selector"), "2"))
    

This strategy will enable you to spend the shortest time waiting for the text to be rendered in the HTML DOM



来源:https://stackoverflow.com/questions/47973741/how-to-determine-if-a-page-is-loaded-using-selenium

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