2013-02-27 4 views
0

일부 레스토랑에서는 테이블을 열어 리뷰를 가져 오려고하지만 일부 레스토랑에는 리뷰가 없으므로 TypeError가 표시됩니다.데이터 스크래핑시 요소가 있는지 확인

나의 현재 코드는 다음 if 문을 구현하는 가장 좋은 방법이 될 것입니다 무엇

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

:

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

내가 좋아하는 뭔가를 할 노력하고있어?

+0

경우 경우/다른 문 다음에 더 콜론이없는 당신이하는'SyntaxError'을 받고해야한다 아무것도 (이것이 의도하지 않은 경우 제외) – TerryA

+0

요소가 있는지 확인하지 마십시오. 그것을 사용하려고 시도한 다음 실패 할 때 적절한 오류를 잡으십시오. [EAFP] (http://docs.python.org/2/glossary.html). – Ben

+0

데이터 스크래핑이란 무엇입니까? restDOM이란 무엇입니까? – octoback

답변

0

벤의 대답은 여기에 정확하지만 나는 실제 코드로 확장 거라고 생각 :

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