from bs4 import BeautifulSoup


def html_to_text(html, target_elements=None):
    """
    Transforms HTML to clean text
    Parameters:
        * html: HTML from a web page (str)
        * target_elements: Elements like `div` or `p` to target pulling text from. (optional) (string)
    Returns:
        Text (string)
    """
    soup = BeautifulSoup(html)

    for script in soup(
        ["script", "style"]
    ):  # remove all javascript and stylesheet code
        script.extract()

    targets = []

    if target_elements:
        targets = soup.find_all(target_elements)

    if target_elements and len(targets) > 3:
        text = " ".join([t.text for t in targets])
    else:
        text = soup.get_text()

    # break into lines and remove leading and trailing space on each
    lines = (line.strip() for line in text.splitlines())
    # break multi-headlines into a line each
    chunks = (phrase.strip() for line in lines for phrase in line.split("  "))
    # drop blank lines
    text = "\n".join(chunk for chunk in chunks if chunk)
    return text