简体   繁体   English

当找不到页面上的文本时,如何中断Python / Selenium中的循环?

[英]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. 我正在尝试制作一个循环,直到在页面上不再找到部分链接文本“ Ticket Request”为止。 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循环。

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()

How about you use a try/catch 你如何使用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 等待30秒后,如果驾驶员找不到链接“ Ticket Request”,它将打印并退出循环

If you want to break a loop, use the break keyword. 如果要中断循环,请使用break关键字。

So, for example: 因此,例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM