2011-08-03 28 views

回答

14

urlparse.urlparse將URL分成協議,地理位置優越,港口,等等,那麼你可以通過.分割位置得到的子域。

url = urlparse.urlparse(address) 
subdomain = url.hostname.split('.')[0] 
+0

工程非常好。我用它像這樣Node = urlparse.urlparse(address).hostname.split('。')[0] – Marko

+3

如果是IP地址會怎麼樣?如果它有一個二級子域呢? – naktinis

+1

子域可能包含多個點,所以'api.test'也是有效的,只要記住這一點。如果你想要一個好的軟件包來檢查'https:// pypi.python.org/pypi/tldextract'。 – sidneydobber

0

一個非常基本的方法,沒有任何完整性檢查可能看起來像:

address = 'http://lol1.domain.com:8888/some/page' 

host = address.partition('://')[2] 
sub_addr = host.partition('.')[0] 

print sub_addr 

當然,這假設當你說「子站點的」你的意思是主機名的第一部分,所以在以下的情況下, 'WWW' 將是子域名:

http://www.google.com/

那是什麼意思?

0

用於提取主機名,我會從使用的urllib2裏urlparse:

>>> from urllib2 import urlparse 
>>> a = "http://lol1.domain.com:8888/some/page" 
>>> urlparse.urlparse(a).hostname 
'lol1.domain.com' 

至於如何提取的子域,你需要支付的情況下,有可能FQDN更長。你如何做到這一點將取決於你的目的。我可能會建議剝去最右邊的兩個組件。

例如

>>> urlparse.urlparse(a).hostname.rpartition('.')[0].rpartition('.')[0] 
'lol1' 
2

你要找的是: http://docs.python.org/library/urlparse.html

例如: ".".join(urlparse('http://www.my.cwi.nl:80/%7Eguido/Python.html').netloc.split(".")[:-2])

會爲你做這項工作(將返回 「www.my」)

+1

這假設主域名有兩個部分 - 在某些情況下會掉下來,例如, '.co.uk'地址。除英國外,以色列,巴西和日本都有正式的二級域名,可能還有其他域名。 –

+0

我的回答使用有效的頂級域名列表處理此問題。 – Acorn

5

修改版本的夢幻般的答案在這裏:How to extract top-level domain name (TLD) from URL

您將需要從here

from __future__ import with_statement 
from urlparse import urlparse 

# load tlds, ignore comments and empty lines: 
with open("effective_tld_names.dat.txt") as tldFile: 
    tlds = [line.strip() for line in tldFile if line[0] not in "/\n"] 

class DomainParts(object): 
    def __init__(self, domain_parts, tld): 
     self.domain = None 
     self.subdomains = None 
     self.tld = tld 
     if domain_parts: 
      self.domain = domain_parts[-1] 
      if len(domain_parts) > 1: 
       self.subdomains = domain_parts[:-1] 

def get_domain_parts(url, tlds): 
    urlElements = urlparse(url).hostname.split('.') 
    # urlElements = ["abcde","co","uk"] 
    for i in range(-len(urlElements),0): 
     lastIElements = urlElements[i:] 
     # i=-3: ["abcde","co","uk"] 
     # i=-2: ["co","uk"] 
     # i=-1: ["uk"] etc 

     candidate = ".".join(lastIElements) # abcde.co.uk, co.uk, uk 
     wildcardCandidate = ".".join(["*"]+lastIElements[1:]) # *.co.uk, *.uk, * 
     exceptionCandidate = "!"+candidate 

     # match tlds: 
     if (exceptionCandidate in tlds): 
      return ".".join(urlElements[i:]) 
     if (candidate in tlds or wildcardCandidate in tlds): 
      return DomainParts(urlElements[:i], '.'.join(urlElements[i:])) 
      # returns ["abcde"] 

    raise ValueError("Domain not in global list of TLDs") 

domain_parts = get_domain_parts("http://sub2.sub1.example.co.uk:80",tlds) 
print "Domain:", domain_parts.domain 
print "Subdomains:", domain_parts.subdomains or "None" 
print "TLD:", domain_parts.tld 

有效的頂級域名列表中爲您提供:

 
Domain: example 
Subdomains: ['sub2', 'sub1'] 
TLD: co.uk 
+0

老人,但好吃! – FredTheWebGuy

+0

比這更好。 –

4

tldextract使得這個任務很容易,然後你可以使用裏urlparse彷彿建議您需要更多信息:

>> import tldextract 
>> tldextract.extract("http://lol1.domain.com:8888/some/page" 
ExtractResult(subdomain='lol1', domain='domain', suffix='com') 
>> tldextract.extract("http://sub.lol1.domain.com:8888/some/page" 
ExtractResult(subdomain='sub.lol1', domain='domain', suffix='com') 
>> urlparse.urlparse("http://sub.lol1.domain.com:8888/some/page") 
ParseResult(scheme='http', netloc='sub.lol1.domain.com:8888', path='/some/page', params='', query='', fragment='') 

請注意,tldextract正確處理子域。

+0

這應該是答案。謝謝。 –