我正在编写一个代码来解析一堆xml文件。基本上是这样的:
for i in range(0, 20855):
urlb = str(i)
url = urla + urlb
trys=0
t=0
while (trys < 3):
try:
cfile = UR.urlopen(url)
trys = 3
except urllib.error.HTTPError as e:
t=t+1
print('error at '+str(time.time()-tstart)+' seconds')
print('typeID = '+str(i))
print(e.code)
print(e.read())
time.sleep (0.1)
trys=0+t
tree = ET.parse(cfile) ##parse xml file
root = tree.getroot()
...do a bunch of stuff with i and the file data
我在调用的一些url中遇到了一个问题,它们实际上不包含破坏我代码的xml文件。我有一个我使用的所有实际数字的列表,而不是显示的范围,但我真的不想遍历所有21000并删除每个失败的数字。有没有更简单的方法来解决这个问题?我从while循环(我必须处理超时)中得到一个错误,如下所示:
b'A non-marketable type was given'
error at 4.321678161621094 seconds
typeID = 31
400
所以我在想,如果while循环返回三个错误,但我不能使用break,那么必须有一个好方法来跳出for循环的迭代。如果t变量是3,while循环下的if/else循环就可以通过吗?你知道吗
你可以试试这个:
关于“算法”问题:您可以在while主体中设置错误状态(例如
last_iteration_successful = False
),然后中断while主体,然后检查for主体中的错误状态,并有条件地中断for主体。你知道吗关于体系结构:通过使用try/except块进行适当的异常处理,为可能发生的所有相关错误准备代码。定义自定义异常类型,然后手动引发它们也很有意义。引发异常会立即中断当前的控制流,它可以节省许多
break
相关问题 更多 >
编程相关推荐