2015-01-05 84 views
-1

我怎麼能提高我在Python代碼,如果我用了很多行類似下面的改進建議這個Python代碼

post_title_tag = soup.find("h1", {"id": "post-title"}) 
if post_title_tag is None: 
    return 

在此功能

def get_post_data(url): 
    browser.get(url) 
    html_source = browser.page_source 
    soup = BeautifulSoup(html_source) 

    post_title_tag = soup.find("h1", {"id": "post-title"}) 
    if post_title_tag is None: 
     return 

    description_tag = soup.find("p", class_="description") 
    if description_tag is None: 
     return 

    datetext_span = description_tag.find("span") 
    if datetext_span is None: 
     return 
+6

這屬於codereview:http://codereview.stackexchange.com/ –

回答

1

一種選擇是包try/except塊中的父函數並使用爲您引發異常的函數。這樣的事情:

class NoSuchTagException(Exception): pass 

def get_tag(parent, name, *args, **kwargs): 
    child = parent.find(name, *args, **kwargs) 
    if child is None: 
     raise NoSuchTagException(name) 
    else: 
     return child 

def get_post_data(url): 
    browser.get(url) 
    html_source = browser.page_source 
    soup = BeautifulSuop(html_source) 

    post_title_tag = get_tag(soup, 'h1', {'id': 'post-title'}) 
    description_tag = get_tag(soup, 'p', class_='description') 
    datetext_span = get_tag(description_tag, 'span')