我正在使用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.
該怎麼辦?我應該使用異常處理嗎?或者有沒有更簡單的方法?
有什麼建議嗎?任何幫助都會非常棒!
@JhonIntriagoThoth:雖然'None'顯然更清潔,但OP在這種情況下希望'null'。 – ThiefMaster 2017-10-27 12:25:23