The code I have works. The last for loop gets reached and choice.click() gets clicked on. The question I have is why the except block gets executed even though the:
if choice.text == call_resource:
choice.click()
break
piece of the code is reached and the choice.click() portion works?
def select_choice(driver, resource_tag):
try:
call_resource = None
access_data = common.retrieve_tag_access_data()
for row in access_data["access_data"]:
if str(row["id"]) == resource_tag:
call_resource = row["row_tag"]["name"]
break
if call_resource is None:
access_data = common.retrieve_fixture_access_data()
for row in access_data["access_data"]:
if str(row["id"]) == resource_tag:
call_resource = row["row_tag"]["name"]
break
menu = driver.find_element_by_css_selector("ul[role='listgrid']")
choices = menu.find_elements_by_css_selector("li[role='choices']")
for choice in choices:
if choice.text == call_resource:
choice.click()
break
except:
error(logger, "unable to select choice")
pass
Because the last for loop works, shouldn't it break entirely out of the function after choice.click() without executing the except: portion of the code?
The except: portion will run only if an Exception occurred inside the try block. You should change the except: line to something like except Exception as e: and print the variable e in some way so you can discover what the problem is.
choices = menu.find_elements_by_css_selector("li[role='choices']")
for choice in choices:
if choice.text == call_resource:
choice.click()
break
Could be replaced with since your only trying to click one element with a certain text why not just try to find it. If it errors out it will go to the exception you provided.
driver.find_element(By.XPATH,f"//li[#role='choices' and contains(text(),{call_resource})]").click()
Also use to find errors use the following.
except Exception as e:
print(str(e))
Related
my program iterate between items, it clicks on the item, then clicks again and moves to the next item.
i am trying to make the program pass on an item if error accurs.
the excepts are inside a while loop, each item code seems like this:
item_1 = driver.find_element_by_id('feed_item_0')
item_1.location_once_scrolled_into_view
if item_1.is_displayed():
item_1.click()
time.sleep(2)
phone_reveal_1 = driver.find_element_by_id('phone_number_0')
contact_seller_1 = driver.find_element_by_id('contact_seller_0')
if phone_reveal_1.is_displayed():
phone_reveal_1.click()
elif contact_seller_1.is_displayed():
contact_seller_1.click()
elif not phone_reveal_1.is_displayed() or contact_seller_1.is_displayed():
continue
at the end i wrote this:
except selenium.common.exceptions.NoSuchElementException:
continue
except selenium.common.exceptions.ElementClickInterceptedException:
continue
except selenium.common.exceptions.StaleElementReferenceException:
continue
so what the code does is when any error accurs no matter if continue, or pass is written, the loop starts all over again from the start. i just want it to skip the item what. am i missing?
for anyone who will have the same issue, problem, was that i have handled the exceptions at the end. every block needs to have its own exception. the code should be like this:
try:
item_1 = driver.find_element_by_id('feed_item_0')
item_1.location_once_scrolled_into_view
if item_1.is_displayed():
item_1.click()
time.sleep(2)
phone_reveal_1 = driver.find_element_by_id('phone_number_0')
contact_seller_1 = driver.find_element_by_id('contact_seller_0')
if phone_reveal_1.is_displayed():
phone_reveal_1.click()
elif contact_seller_1.is_displayed():
contact_seller_1.click()
phone_numbers_1 = driver.find_elements_by_id('phone_number_0')
number_1 = [i.text for i in phone_numbers_1]
except NoSuchElementException:
pass
I'm trying to get input from user, until he press ctrl-c. yet, I can't catch the
error, I think it has something to do with sklearn (I imported it for the rest of the code)
this is the code:
try:
while(True):
i+=1
put = input("\tEnter name of feature number " + str(i) +":\t")
features.append(put)
except KeyboardInterrupt:
print("\n\tFeatures Added!")
sleep(SLEEP)
return None
except:
exit("\nError has occurred, please come back later...")`
Fix your indentation as the following:
try:
while(True):
i+=1
put = input("\tEnter name of feature number " + str(i) +":\t")
features.append(put)
except KeyboardInterrupt:
print("\n\tFeatures Added!")
sleep(SLEEP)
return None
except:
exit("\nError has occurred, please come back later...")
Is there any way to enter try statement once again after catching the exception in the first try?
Now I'm using "while" and "if" statements and it is making the code messy.
Any ideas?
Will try to simplify it as possible, sorry that have no logic...
run = True
tryAgain = True
a=0
while run:
try:
2/a
except Exception:
if tryAgain:
tryAgain = False
a = 1
else:
run = False
You could try using a break statement in your try block:
while True:
try:
# try code
break # quit the loop if successful
except:
# error handling
Considering you are doing this in a while, then you can make use of continue to just continue back to the beginning of the while loop:
tryAgain = True
a=0
while True:
try:
2/a
break # if it worked then just break out of the loop
except Exception:
if tryAgain:
continue
else:
# whatever extra logic you nee to do here
I like using a for loop so that the trying and trying doesn't go on forever. Then the loop's else clause is a place to put the "I give up" code. Here is a general form that will support 'n' retries > 1:
a=0
num_tries = 5
for try_ in range(0,num_tries):
try:
2/a
except Exception:
print("failed, but we can try %d more time(s)" % (num_tries - try_ - 1))
if try_ == num_tries-2:
a = 1
else:
print("YESS!!! Success...")
break
else:
# if we got here, then never reached 'break' statement
print("tried and tried, but never succeeded")
prints:
failed, but we can try 4 more time(s)
failed, but we can try 3 more time(s)
failed, but we can try 2 more time(s)
failed, but we can try 1 more time(s)
YESS!!! Success...
I'm new to Python, so this may not be best practice. I returned to the try statement after triggering the exception by lumping everything into a single function, then recalling that function in the except statement.
def attempts():
while True:
try:
some code
break #breaks the loop when sucessful
except ValueError:
attempts() #recalls this function, starting back at the try statement
break
attempts()
Hope this addresses your question.
I'm using the eval method in my project and I have to handle all the possible exceptions it may raise. I thought that simple try and except would work but when I enter a symbol it doesn't familiar with it stuck.. like eval("5:2").
try:
max = abs(eval(game_function))
except:
while True:
x += (x_f_coordinate - x_0_coordinate) / 1050
try:
max = abs(eval(game_function))
break
except KeyboardInterrupt:
raise
except:
if x < x_f_coordinate:
continue
It's freezing in the 7th line.
Any suggestions?
In the following code for my RPG, I deal with user input and therefore create my code in a way that it can handle errors. When the user enters in a game command such as acquire (which takes two arguments) shown below, the acquire function is called, which tries to use the second part of the split input. If the user only enters 'acquire' and there is no second part to the split string, I expect that the IndexError raises and some text is printed. Again, when my code then tries to access RawInput[1] through the Items dictionary and fails to find it, I expect the KeyError to be raised and the text printed. None of this is happening for me.
When each of these errors should be raising, the error that I'm expecting to occur occurs, but the try/ except block does recover from it.
Items = {
'Rapier': Item('Rapier', 1, [None, None], 2)}
def Acquire(self):
try:
if Pos[0] == self.Pos[0] and Pos[1] == self.Pos[1]:
for i in range(1, 4):
j = i - 1
if self.Type == i and not Inventory[j]:
Inventory[j] = self
self.Pos = None
print(Name, 'picked up the', self.Name)
elif None not in Inventory:
print(Name, 'cannot carry any more!')
else:
print('There is no', RawInput[1].title(), 'here')
except KeyError:
print('That doesn\'t exist!')
except IndexError:
print('Acquire takes two arguments')
def ParseInput():
global RawInput
RawInput = input('> ').lower().split(' ', 1)
if RawInput[0] == 'acquire':
Acquire(Items[RawInput[1].title().strip()])
Could anyone explain to me how to fix my code or explain what is happening?
The errors you're trying to catch won't occur inside of the code itself, but rather when the code is interpreted. putting the try-except around the function call should fix it.
if RawInput[0] == 'acquire':
try:
Acquire(Items[RawInput[1].title().strip()])
except KeyError:
print('That doesn\'t exist!')
except IndexError:
print('Acquire takes two arguments')