[問題] 關於BeautifulSoup遇到沒有資料的時候

作者: brightsu (渣)   2016-11-07 22:56:22
請問一下各位前輩
小弟在用BeautifulSoup遇到了點問題
就是在擷取一個網站資訊的時候會遇到某一個沒有資訊
然後再繼續下去之類的比如像這樣子
resl = soupls.find_all("span",itemprop="ratingValue")
print (resl)
如果這樣下了話會產生這樣的結果
[<span itemprop="ratingValue">5.00</span>]
[]
[<span itemprop="ratingValue">4.73</span>]
[<span itemprop="ratingValue">4.10</span>]
然後如果我只要解取 5.00的部分就必須這樣子
resl = soupls.find_all("span",itemprop="ratingValue")[0].text
print (resl)
但是如果遇上了沒資料的地方就會產生錯誤
IndexError: list index out of range
想請教一下有沒有辦法將空白的資訊帶入一個"0"
另外我有試著用try做,但是可能是語法的問題一直都出現錯誤
是因為我在for裡面做不行嗎?
感謝前輩的指教
作者: s89227 (Kei)   2016-11-07 23:12:00
你的for迴圈跑次數超過了,才會有index out of range所以是要改for的迴圈次數,而不是空著的補0
作者: Yshuan (倚絃)   2016-11-08 09:59:00
所以你的try-except寫成怎樣 沒有作用?
作者: s89227 (Kei)   2016-11-08 10:56:00
重點是不能讓迴圈跑到沒有的地方,這個行為一定噴error
作者: Ricky1123 (Ricky)   2016-11-08 14:36:00
加個if判斷長度不為0再做吧

Links booklink

Contact Us: admin [ a t ] ucptt.com