首页 > 解决方案 > 为什么我会陷入无限循环?

问题描述

我目前正在编写一个 python 脚本,我正在陷入一个无限循环。类似的代码正在工作,但这不是:

while True:
    print ("test")
    sleep(2)
    try:
        doc = html.fromstring(page.content)

        XPATH_PRICE = '//div[@id="product_detail_price"]//content()'
        print(XPATH_PRICE)
        RAW_PRICE = doc.xpath('//div[@id="product_detail_price"]')[0].values()[4]
        print("RAW PRICE:")
        print(RAW_PRICE)
        PRICE = ' '.join(''.join(RAW_PRICE).split()).strip() if RAW_PRICE else None
        print(PRICE)

        data = {
            'PRICE': PRICE,
            'URL': url,
        }

        return data
    except Exception as e:
        print e

标签: pythonloops

解决方案


更改此部分

except Exception as e:
    print e

对此

except Exception as e:
    print(e)
    break

如果你在捕捉异常break的同时 ing ,似乎没有意义,删除这部分:while True

while True:
    print ("test")
    sleep(2)

但是,如果您采用这种while True方法,请break state在循环中放置一个:

while True:
print ("test")
sleep(2)
try:
    doc = html.fromstring(page.content)
    if some_cond:
       break

编辑

让我试着让它更简单。我们有两种方式:

第一种方法

def some_function():
  try:
       #Your expected code here
       return True
  except:
       # will come to this clause when an exception occurs.
       return False

第二种方法

while True:
    if some_cond
        break
    else:
        continue

考虑到您的代码,我建议选择第一种方法。

如果意图仍然保持 -try除非特定条件而不是break例外:

bFlag = False
while bFlag == False:
    try:
        if some_cond:
           bFlag = True
    except:
        continue

推荐阅读