使用Python正则表达式自己实现解析URL各参数

不使用库,自己可以利用正则表达式实现解析域名各部分参数:协议、域名、端口、路径、载荷等。

使用的正则表达式如下:

r'''(?x)\A
([a-z][a-z0-9+\-.]*)://             # Scheme
([a-z0-9\-._~%]+                 # IPv4 host
|\[[a-z0-9\-._~%!$&'()*+,;=:]+\])       # IPv6 host
(:[0-9]+)?                     # Port number
([a-zA-Z0-9\-\/._~%!$&'()*+]+)?        # path
(\?[a-zA-Z0-9&=]+)?                # query
'''               

  例如,对于"https://www.baidu.com/xxx/xxx?s=xxx"网址,解析出来各部分为:

('https', 'www.baidu.com', None, '/xxx/xxx', '?s=xxx')

  

posted @ 2016-12-15 11:30  DerMond  阅读(8349)  评论(0编辑  收藏  举报