我正在迭代一些网络抓取的数据,并试图将结果放入二选一列表中。在这种情况下,下面使用的拆分会引发异常以跳过记录,因为条目中基本上没有"at"。如果我运行10条记录的代码,其中一条记录就是这种情况,那么a_list中有10条,b_list中有9条。我想让所有的东西都正确匹配,并在两个列表中都保留10条记录,但要放在空白或一些字符串中,比如";空";或0添加到异常为true的列表中。在这之后,我希望脚本继续做它的事情。有没有一种简单的方法可以实现这一点?
a_list = []; b_list = [];
for i in range(1,11):
try:
a = driver.find_element_by_xpath('abc').text.split(' at ')[0]
b = driver.find_element_by_xpath('abc').text.split(' at ')[1]
a_list.append(a)
b_list.append(b)
except:
continue
i +=1
您可以在except
块中进行追加。
a_list = []; b_list = [];
for i in range(1,11):
try:
a = driver.find_element_by_xpath('abc').text.split(' at ')[0]
b = driver.find_element_by_xpath('abc').text.split(' at ')[1]
a_list.append(a)
b_list.append(b)
except:
a_list.append(None)
b_list.append(None)
此外,您不需要增加循环变量。for
循环为您完成
试试这个:
for i in range(1, 11):
try:
element_splitted = driver.find_element_by_xpath('abc').text.split(' at ')
except: # No element found
a_list.append(None)
b_list.append(None)
continue
if len(element_splitted) > 1: # it has ' at '
a_list.append(element_splitted[0])
b_list.append(element_splitted[1])
else:
a_list.append(None)
b_list.append(None)
我以前没有用过硒,但我想这就是它的工作原理。首先我检查了一下,发现了元素。然后我检查了一下里面是否有" at "
附加说明:
无需增加i
。
不要使用driver.find_element_by_xpath('abc').text.split(' at ')
零件两次。
不要像我一样使用广泛的异常处理程序-->请检查文档中可能引发的特定异常。