时间:2021-07-01 10:21:17 帮助过:94人阅读
要解析的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