Reputation: 41
How can I retry a code with the try
function?
Idea is:
try:
interaction_type2 = driver.find_elements_by_xpath('web.page.interaction1')
except Error:
interaction_type2 = driver.find_elements_by_xpath('web.page.interaction2')
each time it should add to the interaction +1 and loop through it until there is no error, so try to execute the code each time until it does it successfully. I tried it with a loop but did not get the outcome I want to have.
The code I have so far:
while True:
x = 'web.page.interaction-70"]'
try:
interaction_type2 = driver.find_elements_by_xpath(x) # next 136 then 202, 268
except Exception:
x = x.replace('70', '138')
interaction_type2 = driver.find_elements_by_xpath(x)
interaction_type2.click()
not sure how I can change that on each error, without writing each line.
Upvotes: 0
Views: 25
Reputation: 8829
You can substitute in each value as needed.
for value in [70, 136, 202, 268]:
x = f'web.page.interaction-{value}"]'
try:
interaction_type2 = driver.find_elements_by_xpath(x)
except Exception:
continue
else:
interaction_type2.click()
break
If you need to keep trying values beyond 268, take a look at itertools.count
. You'd loop over itertools.count(start=70, step=66)
. This may be dangerous, though, if every single request fails, giving an infinite loop. You may want to bound your search by instead using range(70, some_high_value, 66)
.
Upvotes: 2