Mahdi
Mahdi

Reputation: 1035

Unable to locate an element because of timeout in selenium python

I'm trying to finding a way to check if a new page/window is opened successfully and has content or not. I know that selenium is not able to check code 200 to see if the page is successfully loaded or not. So what should I do in order to find out if the page is loaded successfully?

while True:
        try:
            driver.find_element_by_css_selector("#showbtn").click()
            print ("Page Loaded Successfully")
            break
        except:
            print ("Page loading failed")
            time.sleep(5)

Upvotes: 1

Views: 615

Answers (2)

KunduK
KunduK

Reputation: 33384

To Click on button Induce WebDriverWait() and element_to_be_clickable() and then click on button.

WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#showbtn"))).click()

OR to check pageload successfully you can induce javascript executor before interacting the the element.

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

You need to add following libraries.

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

Updated code:

while True:
        try:
            WebDriverWait(driver, 20).until(lambda drv: drv.execute_script('return document.readyState == "complete"'))
            print("Page Loaded Successfully")
            WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#showbtn"))).click()                     
            break
        except:
            print ("Page loading failed")
            driver.refresh()

Upvotes: 0

Lucan
Lucan

Reputation: 3615

To check for the presence of an element, you can use WebDriverWait with presence_of_element_located like so:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

element = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.CSS_SELECTOR, ...))
)

That will wait until the element is either found or the wait time is reached (10 seconds in the example)

Upvotes: 1

Related Questions