2012-01-24 2 views
0

html 페이지의 결과에서 사전을 채우기 위해 BeautifulSoup 코드를 작성 중이므로 오류 처리가 필요합니다. 내가 가진 일은 내가하는 일보다 나은 방법이있는 것처럼 느껴진다. 여기에 내가 무엇을 가지고 :BeautifulSoup 찾기 문을 함수에 랩핑하는 방법

rightcol = result.find("div", {"class":"rightcol"}) 

    try: mydict['rating'] = rightcol.find("div", {"class":"rating"}).contents[1]['class'] 
    except AttributeError: pass 

    try: mydict['reviews'] = rightcol.find("span", {"class":"reviews"}).contents 
    except AttributeError: pass 

    try: mydict['address'] = rightcol.find("address").contents 
    except AttributeError: pass 

    (10+ more statements of the same kind) 

내가 함수에 오류 처리를 투입 할 바라고, 무엇인가 그러나

def process(key, code): 
     try: mydict[key] = (execute the BeautifulSoup code, different for each function call) 
     except: pass 

, 내가 어떻게 구문의 확실하지 않다 함수에 BeautifulSoup 명령을 전달합니다. 어떤 아이디어?

답변

2

당신은 dict에 기능을 넣고 필요할 때마다 그들을 호출 할 수 있습니다

def hello(name): 
    return 'Hello, ' + name 

funcMap = {'greet' : hello} 

greeting = funcMap['greet']('Peter') 
print greeting # Hello, Peter 

현재이 코드에 대한 매우 비슷한 일을 할 수 있습니다.

관련 문제