找不到元素时如何用字符串或数值填充异常块中的列表?

How to fill lists in exception block with a string or numeric value when the element is not found?

我正在遍历一些网络抓取的数据,我试图将结果放入两个列表之一。有一种情况,下面使用的拆分会引发异常以跳过记录,因为条目中基本上没有“at”。如果我 运行 10 条记录的代码,并且这是其中一条记录的情况,那么我将在 a_list 中有 10 个,在 b_list 中有 9 个。我想让所有内容都正确匹配并在两个列表中保留 10 条记录,但在异常为真的列表中放入空白或一些字符串,如“null”或 0。在此之后,我希望脚本继续执行它的操作。有没有简单的方法可以做到这一点?

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 loop 会为你做这件事

试试这个:

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)

我以前没有使用过 Selenium,但我想这就是它的工作原理。首先,我检查了它是否找到了元素。然后我检查它是否有" at "在里面。

补充说明:

不需要递增i

不要使用 driver.find_element_by_xpath('abc').text.split(' at ') 部分两次。

不要像我一样使用广泛的异常处理程序 --> 检查文档以了解可能引发的特定异常。