elem = browser.find_element_by_xpath(".//label[@class = 'checkbox' and contains(.,'Últimos 15 días')]/input")if ( elem.is_selected() ): print "already selected"else: elem.click()In my codeelem.click() gets gives an error sometimes. If it does, I need to callelem = browser.find_element_by_xpath again i.e. the first line of the code.
Is there a way to achieve this using exception handling in python.Help will be much appreciated.
- See this answer for exception handling syntax:stackoverflow.com/questions/730764/…cbare– cbare2016-08-21 01:50:52 +00:00CommentedAug 21, 2016 at 1:50
- Possible duplicate ofIn Python try until no errorzondo– zondo2016-08-21 01:51:46 +00:00CommentedAug 21, 2016 at 1:51
4 Answers4
From what I can understand this can be done with exception handling.you could try the following:
elem = browser.find_element_by_xpath(".//label[@class = 'checkbox' and contains(.,'Últimos 15 días')]/input")if ( elem.is_selected() ): print "already selected"else: while True: try: #code to try to run that might cause an error elem.click() except Exception: #code to run if it fails browser.find_element_by_xpath else: #code to run if it is the try is successful break finally: #code to run regardless3 Comments
while True:try: ` #command`except Exception:#error codebreak - sorry still getting use to formatting commentsYou need try/except statement there.
try: elem.click()except Exception: # you need to find out which exception type is raised pass # do somthing else ...generic way to handle exception in python is
try: 1/0except Exception, e: print eSo in your case it would give
try: elem = browser.find_element_by_xpath(".//label[@class = 'checkbox' and contains(.,'Últimos 15 días')]/input")except Exception, e: elem = browser.find_element_by_xpathif ( elem.is_selected() ): print "already selected"else: elem.click()It is better to use the more specific exception type. If you use the generic Exception class, you might catch other exception where you want a different handling
Comments
Look attry andexcept
while elem == None: try: elem = browser.find_element_by_xpath(".//label[@class = 'checkbox' and contains(.,'Últimos 15 días')]/input") if ( elem.is_selected() ): print "already selected" else: elem.click() except Exception, e: elem = NoneObviously using the specific exception that is raised from the click.
1 Comment
Explore related questions
See similar questions with these tags.
