從url中找到域名,首先想到的是用正則,然后尋找相應的類庫。用正則解析有很多不完備的地方,url中有域名,域名后綴一直在不斷增加等。通過google查到幾種方法,一種是用Python中自帶的模塊和正則相結合來解析域名,另一種是使第三方用寫好的解析模塊直接解析出域名。
要解析的url
使用urlparse+正則的方式
topHostPostfix = (
'.com','.la','.io','.co','.info','.net','.org','.me','.mobi',
'.us','.biz','.xxx','.ca','.co.jp','.com.cn','.net.cn',
'.org.cn','.mx','.tv','.ws','.ag','.com.ag','.net.ag',
'.org.ag','.am','.asia','.at','.be','.com.br','.net.br',
'.bz','.com.bz','.net.bz','.cc','.com.co','.net.co',
'.nom.co','.de','.es','.com.es','.nom.es','.org.es',
'.eu','.fm','.fr','.gs','.in','.co.in','.firm.in','.gen.in',
'.ind.in','.net.in','.org.in','.it','.jobs','.jp','.ms',
'.com.mx','.nl','.nu','.co.nz','.net.nz','.org.nz',
'.se','.tc','.tk','.tw','.com.tw','.idv.tw','.org.tw',
'.hk','.co.uk','.me.uk','.org.uk','.vg', ".com.hk")
regx = r'[^/.]+('+'|'.join([h.replace('.',r'/.') for h in topHostPostfix])+')$'
pattern = re.compile(regx,re.IGNORECASE)
print "--"*40
for url in urls:
parts = urlparse(url)
host = parts.netloc
m = pattern.search(host)
res = m.group() if m else host
print "unkonw" if not res else res
運行結果如下:
基本可以接受
urllib來解析域名
print "--"*40
for url in urls:
proto, rest = urllib.splittype(url)
res, rest = urllib.splithost(rest)
print "unkonw" if not res else res
運行結果如下:
會把www.也帶上,還需要進一步解析才可以
使用第三方模塊 tld
print "--"*40
for url in urls:
try:
print get_tld(url)
except Exception as e:
print "unkonw"
運行結果:
結果都可以接受
其他可以使用的解析模塊:
tld
tldextract
publicsuffix
新聞熱點
疑難解答
圖片精選