我在用美丽汤并解析一些 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.
我该怎么办?我应该使用异常处理吗?或者有什么更简单的方法吗?
有什么建议么?任何帮助都会非常好!
处理异常的方法是:
try:
gotdata = dlist[1]
except IndexError:
gotdata = 'null'
当然你也可以检查len()
of dlist
;但处理异常更直观。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)