How to handle TimeoutException in selenium, python
Well, spending some time in my mind, I've found a proper solution.
def login():
browser = webdriver.Firefox()
return browser
def find_element_by_id_u(browser, element):
try:
obj = WebDriverWait(browser, 10).until(
lambda browser : browser.find_element_by_id(element)
)
return obj
#########
try:
driver = login()
find_element_by_id_u(driver, 'the_id')
except TimeoutException:
print traceback.format_exc()
browser.close()
sys.exit(1)
It was so obvious, that I missed it :(
Ami00
Updated on June 15, 2022Comments
-
Ami00 almost 2 years
First of all, I created several functions to use them instead of default "find_element_by_..." and login() function to create "browser". This is how I use it:
def login(): browser = webdriver.Firefox() return browser def find_element_by_id_u(browser, element): try: obj = WebDriverWait(browser, 10).until( lambda browser : browser.find_element_by_id(element) ) return obj ######### driver = login() find_element_by_link_text_u(driver, 'the_id')
Now I use such tests through jenkins(and launch them on a virtual machine). And in case I got TimeoutException, browser session will not be killed, and I have to manually go to VM and kill the process of Firefox. And jenkins will not stop it's job while web browser process is active.
So I faced the problem and I expect it may be resoved due to exceptions handling. I tryed to add this to my custom functions, but it's not clear where exactly exception was occured. Even if I got line number, it takes me to my custom function, but not the place where is was called:
def find_element_by_id_u(browser, element): try: obj = WebDriverWait(browser, 1).until( lambda browser : browser.find_element_by_id(element) ) return obj except TimeoutException, err: print "Timeout Exception for element '{elem}' using find_element_by_id\n".format(elem = element) print traceback.format_exc() browser.close() sys.exit(1) ######### driver = login() driver .get(host) find_element_by_id_u('jj_username').send_keys('login' + Keys.TAB + 'passwd' + Keys.RETURN)
This will print for me the line number of string "lambda browser : browser.find_element_by_id(element)" and it's useles for debugging. In my case I have near 3000 rows, so I need a propper line number.
Can you please share your expirience with me.
PS: I divided my program for few scripts, one of them contains only selenium part, that's why I need login() function, to call it from another script and use returned object in it.