我正在webscraping脚本中运行while True:
循环。我希望scraper以增量循环运行,直到遇到某个错误。一般的问题是当某个条件匹配时,如何跳出while真循环。原样的代码将永远输出第一次运行:
output 1;1
...
output 1;n
这是我的代码的一个最小的可复制的例子。你知道吗
runs = [1,2,3]
for r in runs:
go = 0
while True:
go +=1
output = ("output " + str(r) + ";" +str(go))
try:
print(output)
except go > 3:
break
所需输出为:
output 1;1
output 1;2
output 1;3
output 2;1
output 2;2
output 3;3
output 3;1
output 3;2
output 3;3
[done]
这里不需要
try
和except
。保持简单,只需对go
变量使用一个简单的while
条件。在这种情况下,您甚至不需要break
,因为只要go>=3
,条件将是False
,您将从while循环中出来,并重新启动while循环以获得下一个值r
。你知道吗输出
while的替代方法:正如@chepner所建议的,您甚至不需要
while
,最好使用go
上的for循环相关问题 更多 >
编程相关推荐