我想例外处理“列表索引超出范围”。


107

我正在使用BeautifulSoup并解析一些HTML。

我从每个HTML (使用for循环)中获取特定数据,并将该数据添加到特定列表中。

问题是,某些HTML具有不同的格式(它们中没有我想要的数据)

因此,我尝试使用异常处理并将值添加null到列表中(我应该这样做,因为数据顺序很重要。)

例如,我有一个类似的代码:

soup = BeautifulSoup(links)
dlist = soup.findAll('dd', 'title')
# I'm trying to find content between <dd class='title'> and </dd>
gotdata = dlist[1]
# and what i want is the 2nd content of those
newlist.append(gotdata)
# and I add that to a newlist

并且某些链接没有任何链接<dd class='title'>,所以我想要做的是将字符串添加null到列表中。

错误出现:

list index out of range.

我尝试做的是添加一些像这样的行:

if not dlist[1]:  
   newlist.append('null')
   continue

但这行不通。它仍然显示错误:

list index out of range.

我该怎么办?我应该使用异常处理吗?还是有更简单的方法?

有什么建议?任何帮助都将非常棒!

Answers:


246

处理异常的方法是:

try:
    gotdata = dlist[1]
except IndexError:
    gotdata = 'null'

当然,你也可以检查len()dlist; 但是处理异常更为直观。


1
@JhonIntriagoThoth:虽然None显然更清洁,但是OP 'null'在这种情况下要。
ThiefMaster

很好的解决方案。我在代码中使用了它并记下了它。谢谢!
阿米尔·尤纳斯

31

您有两个选择;处理异常或测试长度:

if len(dlist) > 1:
    newlist.append(dlist[1])
    continue

要么

try:
    newlist.append(dlist[1])
except IndexError:
    pass
continue

如果经常没有第二项,则使用第一项;如果有时没有第二项,则使用第二项。


24

三元就足够了。更改:

gotdata = dlist[1]

gotdata = dlist[1] if len(dlist) > 1 else 'null'

这是一种较短的表达方式

if len(dlist) > 1:
    gotdata = dlist[1]
else: 
    gotdata = 'null'

3

引用ThiefMaster♦有时,我们会得到一个错误,其值指定为'\ n'或null并执行处理ValueError所需的错误:

处理异常是解决之道

try:
    gotdata = dlist[1]
except (IndexError, ValueError):
    gotdata = 'null'

2
for i in range (1, len(list))
    try:
        print (list[i])

    except ValueError:
        print("Error Value.")
    except indexError:
        print("Erorr index")
    except :
        print('error ')

2
当心标签页,Python 3
Gouled Med

2

对于任何对较短方式感兴趣的人:

gotdata = len(dlist)>1 and dlist[1] or 'null'

但是为了获得最佳性能,我建议使用False而不是'null',那么单行测试就足够了:

gotdata = len(dlist)>1 and dlist[1]
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.