打破外循环错误

发布于 2021-01-29 15:02:40

我是python的新手,但收到一条错误消息,指出

打破循环

我知道一个中断只能在一个循环中使用,但是实际上我不知道何时确定循环何时结束。

我如何通过将中断放置在正确的位置来解决此错误(如果这是引起问题的原因)?

码:

# see if we have an available date in this month
try:
    next_available_date = current_date.find_element_by_xpath("following::td[@data-handler='selectDay' and ancestor::div/@id='departureDateContainer']")
    print("Found an available date: {day} {month} {year}".format(day=next_available_date.text, month=month, year=year))
    next_available_date.click()
except NoSuchElementException:
# looping over until the next available date found
        while True:
# click next, if not found, select the next year
            try:
                calendar.find_element_by_class_name("ui-datepicker-next").click()
            except NoSuchElementException:
# select next year
                year = Select(calendar.find_element_by_class_name("ui-datepicker-year"))
                year.select_by_visible_text(str(int(year.first_selected_option.text) + 1))

# reporting current processed month and year
                month = Select(calendar.find_element_by_class_name("ui-datepicker-month")).first_selected_option.text
                year = Select(calendar.find_element_by_class_name("ui-datepicker-year")).first_selected_option.text
                print("Processing {month} {year}".format(month=month, year=year))

try:
    next_available_date = calendar.find_element_by_xpath(".//td[@data-handler='selectDay']")
    print("Found an available date: {day} {month} {year}".format(day=next_available_date.text, month=month, year=year))
    next_available_date.click()
    break
except NoSuchElementException:
    continue
关注者
0
被浏览
88
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    break在python中用于循环内。定位循环应该很容易,因为python代码需要适当缩进。break您的代码在循环外,在try块中。继续的情况与此类似。

    我不确定逻辑,但是可以 通过在while循环中引入/缩进以下try块来解决此问题

    try:
        next_available_date = calendar.find_element_by_xpath(".//td[@data-handler='selectDay']")
        print("Found an available date: {day} {month} {year}".format(day=next_available_date.text, month=month, year=year))
        next_available_date.click()
        break  #this break is in the try block
    except NoSuchElementException:
        continue
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看