python 提取域名、根域名

谁践踏了优雅 2022-10-19 04:20 273阅读 0赞

提取url链接根域名

  1. topRootDomain = (
  2. '.com', '.la', '.cn', '.io', '.co', '.info', '.net', '.org', '.me', '.mobi',
  3. '.us', '.biz', '.xxx', '.ca', '.co.jp', '.com.cn', '.net.cn',
  4. '.org.cn', '.mx', '.tv', '.ws', '.ag', '.com.ag', '.net.ag',
  5. '.org.ag', '.am', '.asia', '.at', '.be', '.com.br', '.net.br',
  6. '.bz', '.com.bz', '.net.bz', '.cc', '.com.co', '.net.co',
  7. '.nom.co', '.de', '.es', '.com.es', '.nom.es', '.org.es',
  8. '.eu', '.fm', '.fr', '.gs', '.in', '.co.in', '.firm.in', '.gen.in',
  9. '.ind.in', '.net.in', '.org.in', '.it', '.jobs', '.jp', '.ms',
  10. '.com.mx', '.nl', '.nu', '.co.nz', '.net.nz', '.org.nz',
  11. '.se', '.tc', '.tk', '.tw', '.com.tw', '.idv.tw', '.org.tw',
  12. '.hk', '.co.uk', '.me.uk', '.org.uk', '.vg', ".com.hk")
  13. def get_domain_root(url):
  14. '''获取根域名。'''
  15. domain_root = ""
  16. try:
  17. # 若不是 http或https开头,则补上方便正则匹配规则
  18. if len(url.split("://")) <= 1 and url[0:4] != "http" and url[0:5] != "https":
  19. url = "http://" + url
  20. reg = r'[^\.]+(' + '|'.join([h.replace('.', r'\.')
  21. for h in topRootDomain]) + ')$'
  22. pattern = re.compile(reg, re.IGNORECASE)
  23. parts = parse.urlparse(url)
  24. host = parts.netloc
  25. m = pattern.search(host)
  26. res = m.group() if m else host
  27. domain_root = "" if not res else res
  28. except Exception as ex:
  29. print("error_msg: " + str(ex))
  30. return domain_root

提取url链接子域名

  1. def get_domain(url):
  2. '''解析域名'''
  3. domain_root = ""
  4. try:
  5. if len(url.split("://")) <= 1 and url[0:4] != "http" and url[0:5] != "https":
  6. url = "http://" + url
  7. parts = parse.urlparse(url)
  8. host = parts.netloc
  9. domain_root = host if host else ''
  10. except Exception as ex:
  11. print("error_msg: " + str(ex))
  12. return domain_root

发表评论

表情:
评论列表 (有 0 条评论,273人围观)

还没有评论,来说两句吧...

相关阅读

    相关 retrofit多个域名

    本来高高兴兴的敲代码,突然来需求说要把升级的接口剥离出去,单独弄一个升级中心,也就意味着有多个根域名。。。 用过retrofit的同学都知道,一般都是初始化一个retrof