Reputation: 125
Im facing a following problem: I need a to randomly generate xpath in a range and click on it, then check if an element is present, if so lunch another function. Else return back and try again.
found = False
while not found:
rndm = random.choice(article_list)
random_link = driver.find_element_by_xpath("html/body/section/div[4]/div[1]/div/aside[%s]/a" % (rndm))
random_link.click()
try:
driver.find_element_by_css_selector("element").is_displayed()
self.check() #function which check if the element is ok
found = True
except NoSuchElementException:
driver.back()
Its working, but it`s using while-loop. I need to restrict it for a certain amount of tries? Any suggestion how to do it? I tried:
for _ in itertools.repeat(None, N):
but when an element is not found after N tries, the test isn't falling and asserting True. And when its found and check by self.check function and everything is just fine I get NoSuchElement error.
Upvotes: 2
Views: 104
Reputation: 89325
"I need to restrict it for a certain amount of tries?"
Since the existing code is working already, you can try to add the new logic while trying to keep the existing codes unchanged as much as possible. One possible way by using a counter variable and checks the counter in addition to checking found
variable, something like this :
found = False
counter = 0
max_tries = 10
while not found and counter < max_tries:
counter += 1
......
try:
......
self.check() #function which check if the element is ok
found = True
except NoSuchElementException:
driver.back()
Upvotes: 1