ram
ram

Reputation: 503

Selenium + Python: How to stop page loading when certain element gets loaded?

The implicit and explicit waits can be used when the page uses AJAX, but I want to stop the loading caused by driver.get() when sufficient elements are loaded. Is it possible to do so because of the driver.get() call returns only when the page finishes loading.

Upvotes: 30

Views: 35682

Answers (2)

Pavel Geveiler
Pavel Geveiler

Reputation: 469

On October 15, 2023, the code from the selected answer does not work, here is the working correctly code block:

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

options = webdriver.ChromeOptions()
options.page_load_strategy = 'none'
driver = webdriver.Chrome(options=options)
wait = WebDriverWait(driver, 20)
driver.get('http://stackoverflow.com/')

wait.until(EC.presence_of_element_located((By.ID, 'content')))
print(driver.find_element(By.ID, 'content').get_attribute('innerHTML'))
driver.execute_script("window.stop(); alert('Content is located, loading stopped!')")
time.sleep(100)

Upvotes: 4

Florent B.
Florent B.

Reputation: 42528

Yes it's possible by setting the pageLoadStrategy capability to none. Then wait for an element to be present and call window.stop to stop the loading:

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

capa = DesiredCapabilities.CHROME
capa["pageLoadStrategy"] = "none"

driver = webdriver.Chrome(desired_capabilities=capa)
wait = WebDriverWait(driver, 20)

driver.get('http://stackoverflow.com/')

wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '#h-top-questions')))

driver.execute_script("window.stop();")

Upvotes: 63

Related Questions