我正在使用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.
我该怎么办?我应该使用异常处理吗?还是有更简单的方法?
有什么建议吗?任何帮助都是很棒的!
发布于 2012-08-10 05:17:13
处理异常是要走的路:
try:
gotdata = dlist[1]
except IndexError:
gotdata = 'null'
当然,您也可以检查len()
Of dlist
;但是处理异常更直观。
发布于 2012-08-10 05:17:43
您有两个选项;要么处理异常,要么测试长度:
if len(dlist) > 1:
newlist.append(dlist[1])
continue
或
try:
newlist.append(dlist[1])
except IndexError:
pass
continue
如果经常没有第二项,则使用第一项;如果有时没有第二项,则使用第二项。
发布于 2012-08-10 05:22:06
三元就够了。改变:
gotdata = dlist[1]
至
gotdata = dlist[1] if len(dlist) > 1 else 'null'
这是一种简短的表达方式。
if len(dlist) > 1:
gotdata = dlist[1]
else:
gotdata = 'null'
https://stackoverflow.com/questions/11902458
复制相似问题