JStew
JStew

Reputation: 457

How can I break a loop in Python/selenium when text on a page is not found?

I'm trying to make a loop that keeps going until the partial link text "Ticket Request" is no longer found on the page. I've looked into options, but I don't know how to actually check whether or not a link is found.

Here is the basic idea of the loop I'm creating. I have a for loop with a high limit temporarily until I find a better solution.

for i in range(100):
    driver.get('https://www.webpage.com')
    wait = ui.WebDriverWait(driver, 30)
    wait.until(lambda driver: driver.find_element_by_partial_link_text('Ticket Request'))
    driver.find_element_by_partial_link_text('Requesting a Restricted Lead').click()

Upvotes: 0

Views: 2572

Answers (2)

Amey
Amey

Reputation: 8548

How about you use a try/catch

try:
  wait.until(lambda driver: driver.find_element_by_partial_link_text('Ticket Request'))
except: 
  print "Did not find the element, I can now do what I want"
  #break #if you really want to break out of something

After waiting for 30 seconds if the driver cannot find the link "Ticket Request", it will print and break out of the loop

Upvotes: 1

sapi
sapi

Reputation: 10224

If you want to break a loop, use the break keyword.

So, for example:

for i in range(100):
   ... # do stuff
   if some_condition:
       break

Upvotes: 0

Related Questions