2013-02-27 56 views
0

我想拉開一些餐廳的開放表的評論,但我得到TypeError,因爲這些餐廳有些沒有評論。檢查元素是否存在時,刮數據

我當前的代碼是:

ratings = restDOM.by_id("RestPopLabel_ReviewsFormat")[0].attributes 
ratings = ratings['title'] 

我試着這樣做:

if restDOM.by_id("RestPopLabel_ReviewsFormat")[0] is present 
    ratings = restDOM.by_id("RestPopLabel_ReviewsFormat")[0].attributes 
    ratings = ratings['title'] 
else 
    ratings = 'not available' 

什麼是執行if語句的最好方法?

+0

如果有什麼事情你應該得到一個'SyntaxError',因爲你的if/else語句後沒有冒號(除非這是無意的) – TerryA 2013-02-27 08:41:47

+0

不要檢查元素是否存在。嘗試使用它,然後在失敗時捕獲相應的錯誤,[EAFP](http://docs.python.org/2/glossary.html)。 – Ben 2013-02-27 08:42:14

+0

什麼是更精確的數據抓取?什麼是restDOM? – octoback 2013-02-27 10:58:42

回答

0

Ben的答案是正確的在這裏,但我想我會用實際的代碼擴展:

try: 
    ratings = restDOM.by_id("RestPopLabel_ReviewsFormat")[0].attributes 
    ratings = ratings['title'] 
except KeyError: 
    ratings = 'not available'