python实现切割url得到域名、协议、主机名等各个字段的例子

yipeiwu_com6年前Python基础

有一个需求就是需要对url进行进一步的划分得到详细的各个字段信息,下面是简单的实现:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
'''
__Author__:沂水寒城
功能: 对URL进行分割,基于urlparse, publicsuffix, urllib编写
'''
from urlparse import urlparse
import codecs
from publicsuffix import PublicSuffixList
from urllib import splitport
import re
 
 
def domain_split(server_domain):
  '''
  server_domain为网站所用服务名+域名
  分割域名, 得到前缀(服务名)、主机域名、后缀(顶级域名)
    输入www.baidu.com,输出'www', 'baidu', 'com'
    输入172.31.137.240,输出'', '172.31.137.240', ''
  '''
  PSL_FILE = codecs.open('public_suffix_list.dat', encoding='utf8')
  psl = PublicSuffixList(PSL_FILE)
  domain = psl.get_public_suffix(server_domain)
  # 取域名的第一个字段,即第一个'.'之前的为主机域名, 后面为顶级域名,前面为所使用的服务
  if '.' in domain:
    server = server_domain[:-len(domain)]
    host = domain[:domain.index('.')]
    top = domain[domain.index('.'):]
    hostname = server + host + top
  else: # 说明提取域名失败,例如172.31.137.240等IP形式,此时全部当作主机域名
    server = ''
    host = server_domain
    top = ''
    hostname = server_domain
  return server, host, top, hostname
 
 
def url_split_new(url):
  '''
  url分割
  '''
  if not url.startswith('http'): # 补全协议,否则urlparse出错
    url = 'http://' + url
  parts = urlparse(url)
  # 服务+域名'www.baidu.api.com.cn'切分
  server, host, top, hostname = domain_split(parts.netloc)
  host, port = splitport(host)
  if port == None: port = ''
  return {'protocol': parts.scheme, 'hostname': hostname, 'path': parts.path}
 
 
if __name__ == '__main__':
  print url_split_new('http://www.baidu.com/')
  print url_split('http://www.baidu.com/')

以上这篇python实现切割url得到域名、协议、主机名等各个字段的例子就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python Django 简单分页的实现代码解析

Python Django 简单分页的实现代码解析

这篇文章主要介绍了Python Django 简单分页的实现代码解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 models.py...

python中split方法用法分析

本文实例讲述了python中split方法用法。分享给大家供大家参考。具体分析如下: split 是非常重要的字符串方法,它是join的逆方法,用来将字符串分割成序列 >>...

Python安装使用命令行交互模块pexpect的基础教程

一、安装 1、安装easy_install工具 wget http://peak.telecommunity.com/dist/ez_setup.py python ez_se...

对Python中plt的画图函数详解

1、plt.legend plt.legend(loc=0)#显示图例的位置,自适应方式 说明: 'best' : 0, (only implemented for ax...

Python字典操作详细介绍及字典内建方法分享

创建 方法一: >>> dict1 = {} >>> dict2 = {'name': 'earth', 'port': 80} >>...