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 ステートメントを実装する最良の方法は何でしょうか?

4

1 に答える 1

0

ベンの答えはここでは正しいですが、私は実際のコードで拡張すると思いました:

try:
  ratings = restDOM.by_id("RestPopLabel_ReviewsFormat")[0].attributes
  ratings = ratings['title']
except KeyError:
  ratings = 'not available'
于 2013-02-27T09:19:07.893 に答える