python - 为什么我会陷入无限循环?
问题描述
我目前正在编写一个 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
解决方案
更改此部分:
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
推荐阅读
- java - 使用Java(Apache poi-4.1.1)将excel中单元格的背景颜色设置为灰色并将边框设置为黑色
- python - 如何为每个对象的实例分配不同的进程?Python
- flutter - 如何从 sqflite 表中获取数据以显示在列表视图中?
- c# - 无法在此范围内声明名为“列”的本地参数,因为该名称位于封闭的本地范围内以定义本地或参数
- javascript - 为没有 URL 的引导卡实现 JavaScript navigator.share()
- node.js - 如何获取两个日期之间的数据 | NodsJs | MongoDB
- python - Windows Python中的PyAudio安装错误
- firebase - Firebase 部署在本地工作,但不在 GitHub Action 上
- flutter - 是否可以将客户端证书传递给服务器以进行身份验证?
- r - Power BI 报表服务器 - 计划刷新 SQL 源但使用 R 脚本转换