小编典典

打破外循环错误

python

我是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

阅读 178

收藏
2021-01-20

共1个答案

小编典典

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
2021-01-20