How to stop a page loading from Selenium in chrome?


We can stop a page loading with Selenium webdriver in Chrome browser by using the JavaScript Executor. Selenium can execute JavaScript commands with the help of the executeScript command.

To stop a page loading, the command window.stop() is passed as a parameter to the executeScript method. Also, for the Chrome browser we have to configure the pageLoadStrategy to none value and wait for the web element to be available.

Finally, we have to invoke window.stop.

Syntax

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

Example

Code Implementation with JavaScript Executor

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
#configure pageLoadStrategy to none
c = DesiredCapabilities.CHROME
c["pageLoadStrategy"] = "none"
#set chromodriver.exe path
driver = webdriver.Chrome(executable_path="C:\chromedriver.exe",
desired_capabilities=c)
#explicit wait
w = WebDriverWait(driver, 15)
#launch URL
driver.get("https://www.google.com/")
#expected condition
w.until(EC.presence_of_element_located((By.CLASS_NAME, 'gLFyf')))
#JavaScript Executor to stop page load
driver.execute_script("window.stop();")

We can also stop the page load with the help of the set_page_load_timeout method and passing the time in seconds as a parameter to this method. For example, if the time is 0.1 seconds, a TimeoutException shall be raised if the page load consumes greater than 0.1 second.

Syntax

driver.set_page_load_timeout(0.1)

Example

from selenium import webdriver
#set chromodriver.exe path
driver = webdriver.Chrome(executable_path="C:\chromedriver.exe")
#set page load timeout
driver.set_page_load_timeout(0.1)
#launch URL
driver.get("https://accounts.google.com/")
#close browser
driver.close()

Output

Updated on: 06-Apr-2021

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements