import requests


def extract_token(coin_name):
    """Extract the contract address of the token coin_name based
    on etherscan.io database. The name coin_name must be the one contained in
    its coinmarketcap's url.

    Ex : For BAT, we have the following url on coinmarketcap :
    https://coinmarketcap.com/currencies/basic-attention-token/
    Therefore, coin_name would be "basic-attention-token"

    Args:
        coin_name (str): Name of the crypto

    Raises:
        ValueError: If the name is unknown
        ValueError: If the crypto is not registered on
                    Ethereum

    Returns:
        str: The corresponding token address ("0x0d87...")
    """

    cname = coin_name.lower()
    url = f"https://coinmarketcap.com/currencies/{cname}/"
    r = requests.get(url)
    if r.status_code != 200:
        raise ValueError("Unknown coin name. Please check the url "
                         "on coinmarketcap.com")
    else:
        html_page = r.text
        n = html_page.find("https://etherscan.io/token")

        if n == -1:
            raise ValueError("Error : Coin not on Ethereum platform")
        else:
            token = html_page[n+27:n+69]
            return token