def get_domain(url, tlds):
    url_elements = urlparse(url)[1].split('.')
for i in range(-len(url_elements), 0):
    last_i_elements = url_elements[i:]
candidate = '.'.join(last_i_elements)
wildcard_candidate = '.'.join(['*'] + last_i_elements[1:])
exception_candidate = '!' + candidate
if exception_candidate in tlds:
    return '.'.join(url_elements[i:])
if candidate in tlds or wildcard_candidate in tlds:
    return '.'.join(url_elements[i - 1:])
raise ValueError('Domain not in global list of TLDs')
print(get_domain('http://abcde.co.uk', tlds))
How to extract top-level domain name (TLD) from URL