I've written a simple function. The purpose of go_to_url
so we can set a max load time for a page. If a page does not load within the timeout_limit
, then we will try loading the page again. However, I am getting an error if the page does fail to load within the time frame and goes into the exception.
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import TimeoutException
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import WebDriverException
def go_to_url(driver, url, timeout_limit):
while True:
try:
driver.set_page_load_timeout(timeout_limit)
driver.get(url)
break;
except TimeoutException:
driver.send_keys(Keys.ESCAPE)
print('Failed to load, reloading page')
options = webdriver.ChromeOptions()
options.add_argument("--incognito")
driver = webdriver.Chrome(options=options)
go_to_url(driver, "http://www.emba.com.tw/", 4)
Error:
Traceback (most recent call last):
File "test.py", line 15, in go_to_url
driver.get(url)
File "C:\Users\pc\AppData\Local\Programs\Python\Python37-32\lib\site-packages
\selenium\webdriver\remote\webdriver.py", line 333, in get
self.execute(Command.GET, {'url': url})
File "C:\Users\pc\AppData\Local\Programs\Python\Python37-32\lib\site-packages
\selenium\webdriver\remote\webdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "C:\Users\pc\AppData\Local\Programs\Python\Python37-32\lib\site-packages
\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.TimeoutException: Message: timeout
(Session info: chrome=71.0.3578.98)
(Driver info: chromedriver=2.45.615291 (ec3682e3c9061c10f26ea9e5cdcf3c53f3f743
87),platform=Windows NT 6.3.9600 x86_64)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "test.py", line 25, in <module>
go_to_url(driver, "http://www.emba.com.tw/", 4)
File "test.py", line 18, in go_to_url
driver.send_keys(Keys.ESCAPE)
AttributeError: 'WebDriver' object has no attribute 'send_keys'