import requests
from bs4 import BeautifulSoup


def get_nethandle(url):
    """Retrieves an ARIN nethandle from an IPinfo network webpage.

    Args:
        url: The URL for an IPinfo network webpage.

    Returns:
        A string containing the ARIN nethandle. If no nethandle is found, None
        is returned. An example is below:

            NET-107-167-160-0-1
    """
    # Local variables
    result = None
    headers =   {   'Host': 'ipinfo.io',
                    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:68.0) Gecko/20100101 Firefox/68.0',
                    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
                    'Accept-Language': 'en-US,en;q=0.5',
                    'Accept-Encoding': 'gzip, deflate',
                    'Connection': 'close',
                    'Upgrade-Insecure-Requests': '1'
                }

    # Request nethandle and process
    handle_req = requests.get(url, headers=headers)
    soup_pre = BeautifulSoup(handle_req.text, 'html.parser')
    for tag in soup_pre.find_all('pre', text=True):
        if 'NetHandle' in tag.text:
            for x in range(0,str(tag.text).count('\n')+1):
                line = str(tag.text).split('\n')[x]
                if 'NetHandle' in line:
                    handle = line.split('NetHandle:')[1].lstrip()
                    result = handle

    # Return result
    return result