2009-10-05 4 views

답변

24

호스트 이름을 얻는 것은 충분히 urlparse을 사용하여 쉽게 : "루트 도메인"그러나 더 문제가 될 것입니다 얻기

hostname = urlparse.urlparse("http://www.techcrunch.com/").hostname 

, 그것이 통 사적 의미에서 정의되지 않기 때문에. "www.theregister.co.uk"의 루트 도메인은 무엇입니까? 기본 도메인을 사용하는 네트워크는 어떻습니까? "devbox12"는 유효한 호스트 이름이 될 수 있습니다. 이 처리하는

한 가지 방법은 입니다뿐만 아니라 개인 도메인 (".NET", ".ORG"예 ".COM") 실제 최상위 도메인 모두를 카탈로그 시도 Public Suffix List을 사용하는 것입니다 TLD와 같이을 사용하십시오 (예 : ".co.uk"또는 ".github.io"). 당신은 publicsuffix2 라이브러리를 사용하여 파이썬에서 PSL에 액세스 할 수 있습니다 : 이것은 내 목적을 위해 일한

import publicsuffix 
import urlparse 

def get_base_domain(url): 
    # This causes an HTTP request; if your script is running more than, 
    # say, once a day, you'd want to cache it yourself. Make sure you 
    # update frequently, though! 
    psl = publicsuffix.fetch() 

    hostname = urlparse.urlparse(url).hostname 

    return publicsuffix.get_public_suffix(hostname, psl) 
+0

이 코드의 호스트 이름 = ".". join (len (호스트 이름 [-2]) <4 및 호스트 이름 [-3 :] 또는 호스트 이름 [-2 :]) 작동합니까? Thanks – Joozty

+0

@Joozty - 부정적 인덱스는 마지막부터 시작하므로'hostname [-2]'는 마지막 항목 (이 경우 점으로 구분 된 호스트 이름)의 마지막 항목을 의미합니다. 'foo와 bar 또는 baz'는 삼항처럼 작동합니다 : "foo"가 참이면 "bar"를 반환하십시오; 그렇지 않으면 "baz"를 반환합니다. 마지막으로,'hostname [-3 :]'는 마지막 세 부분을 의미합니다. 모두 함께, 이것은 "호스트 이름의 마지막 부분이 4 자보다 짧으면 마지막 세 부분을 사용하여 점으로 결합합니다. 그렇지 않으면 마지막 두 부분 만 가져 와서 함께 결합하십시오." –

+0

어떤 이유로 모듈을 설치 한 후에도 Python 3에서'ImportError : get_public_suffix '이름을 가져올 수 없습니다. 어떤 답변도 온라인이나 문서에서 찾을 수 없으므로 대신 그냥 "tldextract"를 사용하십시오! 물론, 나는'sudo pip3 install tldextract'를 먼저해야만했다. – Nagev

-4

. 나는 그것을 나눌 것이라고 생각했다.

".".join("www.sun.google.com".split(".")[-2:]) 
+3

"www.sun.google.co.uk"테스트는 어떻습니까? "google.co.uk"대신 "co.uk"이 표시됩니다 ... 건배! –

+3

예, Ben Blank의 접근 방식을 사용하십시오. 내가 2010 년에 생각한 것이 확실하지 않음 :-) –

0

______Using 파이썬 3.3 아니라 2.x는 ________

나는 벤 빈의 대답에 작은 일을 추가하고 싶습니다.

from urllib.parse import quote,unquote,urlparse 
u=unquote(u) #u= URL e.g. http://twitter.co.uk/hello/there 
g=urlparse(u) 
u=g.netloc 

지금까지 도메인 이름은 urlparse입니다.

어떤 것이 최상위 도메인인지 알아야하는 하위 도메인을 제거하려면 삭제해야합니다. 예 : 위의 http://twitter.co.uk-co.uk은 TLD로 http://sub.twitter.com에는 TLD로 .com이고 서브 도메인은 sub입니다.

그래서 우리는 모두 tlds 인 파일/목록을 가져와야합니다.

tlds = load_file("tlds.txt") #tlds holds the list of tlds

hostname = u.split(".") 
if len(hostname)>2: 
    if hostname[-2].upper() in tlds: 
     hostname=".".join(hostname[-3:]) 
    else: 
     hostname=".".join(hostname[-2:]) 
else: 
    hostname=".".join(hostname[-2:]) 
URL의
5

일반적인 구조 :

scheme://netloc/path;parameters?query#fragment

TIMTOWTDI 모토 으로 : urlparse를 사용

,

귀하의 경우3210
>>> from urllib.parse import urlparse # python 3.x 
>>> parsed_uri = urlparse('http://www.stackoverflow.com/questions/41899120/whatever') # returns six components 
>>> domain = '{uri.netloc}/'.format(uri=parsed_uri) 
>>> result = domain.replace('www.', '') # as per your case 
>>> print(result) 
'stackoverflow.com/' 

tldextract를 사용

>>> import tldextract # The module looks up TLDs in the Public Suffix List, mantained by Mozilla volunteers 
>>> tldextract.extract('http://forums.news.cnn.com/') 
ExtractResult(subdomain='forums.news', domain='cnn', suffix='com') 

:

>>> extracted = tldextract.extract('http://www.techcrunch.com/') 
>>> '{}.{}'.format(extracted.domain, extracted.suffix) 
'techcrunch.com' 

tldextract on the other hand knows what all gTLDs [Generic Top-Level Domains] and ccTLDs [Country Code Top-Level Domains] look like by looking up the currently living ones according to the Public Suffix List. So, given a URL, it knows its subdomain from its domain, and its domain from its country code.

힘내라!:)

2

다음 스크립트는 완벽하지는 않지만 표시/단축 목적으로 사용할 수 있습니다. 타사 종속성을 피하고 싶다면/특히 원격으로 데이터를 가져 와서 캐싱해야 할 경우 프로젝트에서 사용하는 스크립트를 따르십시오. 가장 일반적인 도메인 확장을 위해 도메인의 마지막 두 부분을 사용하고 덜 알려진 도메인 확장의 나머지 부분에 대해 마지막 세 부분을 남깁니다.

from urlparse import urlparse 

def extract_domain(url): 
    parsed_domain = urlparse(url) 
    domain = parsed_domain.netloc or parsed_domain.path # Just in case, for urls without scheme 
    domain_parts = domain.split('.') 
    if len(domain_parts) > 2: 
     return '.'.join(domain_parts[-(2 if domain_parts[-1] in { 
      'com', 'net', 'org', 'io', 'ly', 'me', 'sh', 'fm', 'us'} else 3):]) 
    return domain 

extract_domain('google.com')   # google.com 
extract_domain('www.google.com')  # google.com 
extract_domain('sub.sub2.google.com') # google.com 
extract_domain('google.co.uk')  # google.co.uk 
extract_domain('sub.google.co.uk') # google.co.uk 
extract_domain('www.google.com')  # google.com 
extract_domain('sub.sub2.voila.fr') # sub2.voila.fr 
0
def get_domain(url): 
    u = urlsplit(url) 
    return u.netloc 

def get_top_domain(url): 
    u""" 
    >>> get_top_domain('http://www.google.com') 
    'google.com' 
    >>> get_top_domain('http://www.sina.com.cn') 
    'sina.com.cn' 
    >>> get_top_domain('http://bbc.co.uk') 
    'bbc.co.uk' 
    >>> get_top_domain('http://mail.cs.buaa.edu.cn') 
    'buaa.edu.cn' 
    """ 
    domain = get_domain(url) 
    domain_parts = domain.split('.') 
    if len(domain_parts) < 2: 
     return domain 
    top_domain_parts = 2 
    # if a domain's last part is 2 letter long, it must be country name 
    if len(domain_parts[-1]) == 2: 
     if domain_parts[-1] in ['uk', 'jp']: 
      if domain_parts[-2] in ['co', 'ac', 'me', 'gov', 'org', 'net']: 
       top_domain_parts = 3 
     else: 
      if domain_parts[-2] in ['com', 'org', 'net', 'edu', 'gov']: 
       top_domain_parts = 3 
    return '.'.join(domain_parts[-top_domain_parts:]) 
관련 문제