检查抓取数据时元素是否存在
我正在尝试从开放平台获取一些餐厅的评价,但因为有些餐厅没有评价,所以出现了类型错误。
我现在的代码是:
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语句才是最好的方法呢?
1 个回答
1
Ben的回答是对的,不过我想用实际的代码来进一步解释一下:
try:
ratings = restDOM.by_id("RestPopLabel_ReviewsFormat")[0].attributes
ratings = ratings['title']
except KeyError:
ratings = 'not available'