有关改进此Python代码的建议

时间:2015-01-05 14:20:50

标签: python beautifulsoup

如果我使用如下所示的很多行

,我怎么能在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

1 个答案:

答案 0 :(得分: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')