我有一个for
循环,可以从网站上的电子表格中提取数据,并将数据写入文本文件。电子表格通常不会更新,因此是空白的。当电子表格为空白时,我的循环失败。如果失败,我将如何跳过循环?
for row in aatable.findAll('tr')[1:]:
items = row.text.replace(u"kn","") # remove kn so items line up when unpacking
time, ais_source, speed_km, lat, lon, course = items.split()[1:7]
data = items.split()[1:7]
text_file.write(str(data)+ ",Adams Challenge"+'\n')
答案 0 :(得分:2)
将aatable.findAll('tr')
分配给变量data
并检查if data
以获取空列表:
data = aatable.findAll('tr')
if data: # will be False for []
for row in data[1:]:
items = row.text.replace(u"kn","") # remove kn so items line up when unpacking
time, ais_source, speed_km, lat, lon, course = items.split()[1:7]
data = items.split()[1:7]
text_file.write(str(data)+ ",Adams Challenge"+'\n')
或使用try/except
来抓住ValueError
:
try:
for row in aatable.findAll('tr')[1:]:
items = row.text.replace(u"kn","") # remove kn so items line up when unpacking
time, ais_source, speed_km, lat, lon, course = items.split()[1:7]
data = items.split()[1:7]
text_file.write(str(data)+ ",Adams Challenge"+'\n')
except ValueError:
pass