简体   繁体   中英

How to stop test if page taking too long to load in selenium python

I'm testing a website and all is good with me except when the page is taking too much time then selenium keeps on searching for the element. I've tried to use driver.set_page_load_timeout(5) but still keeps on loading forever.
Here is the code:

from selenium import webdriver
from selenium.common.exceptions import *
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
import time, os,re, datetime
import logging




class SanityTest():

def login_test(self):
    driver_location = 'C:\\chromedriver.exe'
    os.environ["webdriver.chrome.driver"] = driver_location
    driver = webdriver.Chrome(driver_location)
    driver.maximize_window()
    driver.implicitly_wait(0)
    baseURL = driver.get("https://www.example.com/")
    logging.basicConfig( format = '%(asctime)s: %(levelname)s: %(message)s',datefmt='%m/%d/%Y %I:%M:%S %p'
                        ,level=logging.INFO)
    driver.set_page_load_timeout(2)

    #Is Platform is reachable?:-
    try:
        if WebDriverWait(driver, 1).until(
                EC.visibility_of_element_located((By.XPATH, "//button[contains(@class,'button')]"))):
            logging.info("Success")
    except:
        pass

    try:
        if WebDriverWait(driver, 1).until(
                EC.visibility_of_element_located((By.XPATH, '//span[@jsselect="heading" and @jsvalues=".innerHTML:msg"]'))):

            logging.error('Failure: Unable to reach platform! ==> ' + str(driver.find_element_by_xpath('//span[@jsselect="heading" and @jsvalues=".innerHTML:msg"]').text))
            return
    except :
        print("Page is taking too long to load")
        return



 ff = SanityTest()
 ff.login_test()

Functionally set_page_load_timeout() works and should have worked for you:

driver.set_page_load_timeout(2)

You can find a detailed discussion in How to set the timeout of 'driver.get' for python selenium 3.8.0?

However it is worth to mention that set_page_load_timeout() is applicable only after 'document.readyState' is equal to "complete" is achieved. Perhaps in this usecase 'document.readyState' equals to "complete" is achieved pretty late.


Solution

As a solution instead of using the default pageLoadStrategy which is by default set to normal , you can set pageLoadStrategy as eager ie interactive as follows:

caps["pageLoadStrategy"] = "eager"  #  interactive

You can find a detailed discussion in How to make Selenium not wait till full page load, which has a slow script?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM