Python Forum

Full Version: how do i loop a "def ..." when error occurs?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
i'm automating some of my website monitoring work with python+selenium. the relevant part of the code looks like this:

import time
import schedule
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

def job():

        browser = webdriver.Chrome('W:\selenium\chromedriver')

        browser.get('https://xxxxxx.com')
        browser.maximize_window()

        # logging in
        browser.find_element_by_id("name").send_keys("username")
        browser.find_element_by_id("pwd").send_keys("password")
        browser.find_element_by_id("btn_login").click()

        # ...blah blah blah...

        browser.close()

schedule.every().day.at("09:00").do(job)

while True:
        schedule.run_pending()
        time.sleep(1)
because the website is poorly built, the log-in elements have a chance to never load correctly no matter the amount of time given, only a refresh would correct them. that means, most of the time, the script runs fine. but in some cases, the code terminates with error message "no such element". i've looked into "try" statements but only know how to use it in execution phase. so is there a way to incorporate "try" in the definition statement? or is there a better way to loop the script on error? cheers.