我正在使用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.
我该怎么办?我应该使用异常处理吗?还是有更简单的方法?
有什么建议?任何帮助都将非常棒!
None
显然更清洁,但是OP'null'
在这种情况下要。