How to load page until specific element found selenium python

Viewed 78

Is there a way to set timeout when specific element in webpage loads

Notice: I am talking about loading webpage using driver.get() method

I tried setting page loads timeout to 10s for example and check whether element is present but if it is not present i'll have to load it from start.

Edit:

Clearly said that I don't want to load full url

I want driver.get() to load url until element found and then stop loading more from url

In your examples you used simply driver.get() method which will load full url and then execute next command. One way is to use driver.set_page_load_timeout()

3 Answers

Edit:

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

op = Options()
op.page_load_strategy = 'none'
driver = webdriver.Chrome(options=op)
driver.get(URL)
WebDriverWait(driver, 10).until(
    EC.presence_of_element_located(
        (By.XPATH, '//div')))
driver.execute_script("window.stop();")

PS. You will keep getting off-topic answers if you post vague questions without a line of code.

webdriver will wait for a page to load by default. It does not wait for loading inside frames or for ajax requests. It means when you use .get('url'), your browser will wait until the page is completely loaded and then go to the next command in the code. But when you are posting an ajax request, webdriver does not wait and it's your responsibility to wait an appropriate amount of time for the page or a part of page to load; so there is a module named expected_conditions.

When the element is not found you get an error so you can use " try " untill the element is found:

while True:
    try:
        element = driver.find_element(by=By.<Your Choice>, value=<Name or Xpath or ...>)
    except:
        time.sleep(1)

It tries till the element is found

Related