基于python(urlparse)模板的使用方法总结

有人说: "要么旅行,要么读书,身体和灵魂,必须有一个在路上。 "这次川西之行我们走进四姑娘山。四姑娘山,是四座并立的山峰,山体陡峭,直指蓝天,冰雪覆盖,银光照人,享有 "蜀山皇后 "的美誉。

一、简介

urlparse模块用户将url解析为6个组件,并以元组形式返回,返回的6个部分,分别是:scheme(协议)、netloc(网络位置)、path(路径)、params(路径段参数)、query(查询)、fragment(片段)。

二、功能列举

1、urlparse.urlparse()(将url解析为组件,url必须以http://开头)

>>> urlparse.urlparse("https://i.cnblogs.com/EditPosts.aspx?opt=1")
ParseResult(scheme='https', netloc='i.cnblogs.com', path='/EditPosts.aspx', params='', query='opt=1', fragment='')

返回的元素中也会包含其他属性,比如(username,password,hostname,port):

>>> urlparse.urlparse("https://i.cnblogs.com:80/EditPosts.aspx?opt=1").port
80
>>> urlparse.urlparse("https://i.cnblogs.com:80/EditPosts.aspx?opt=1").hostname
'i.cnblogs.com'

2、urlparse.urljoin()(将相对的地址组合成一个url,对于输入没有限制,开头必须是http://,否则将不组合前面)

>>> urlparse.urljoin("https://i.cnblogs.com","EditPosts.aspx")
'https://i.cnblogs.com/EditPosts.aspx'

3、urlparse.urlsplit() :返回一个5个元素的元组,适用于遵循RFC2396的URL

>>> urlparse.urlsplit("https://i.cnblogs.com:80/EditPosts.aspx?opt=1")
SplitResult(scheme='https', netloc='i.cnblogs.com:80', path='/EditPosts.aspx', query='opt=1', fragment='')

4、urlparse.urlunsplit() :使用urlsplit的格式组合成一个url,传递的元素必须是5个,或者直接将分解的元组重新组合

>>> urlparse.urlunsplit(("https","i.cnblogs.com","EditPosts.aspx","a=a","b=b"))
'https://i.cnblogs.com/EditPosts.aspx?a=a#b=b'
>>> parse = urlparse.urlsplit("https://i.cnblogs.com:80/EditPosts.aspx?opt=1")
>>> urlparse.urlunsplit(parse)
'https://i.cnblogs.com:80/EditPosts.aspx?opt=1'

5、urlparse.urlunparse() :使用urlparse的格式组合成一个url,可以直接将urlparse的返回传递组合

>>> parse = urlparse.urlparse("https://i.cnblogs.com:80/EditPosts.aspx?opt=1")
>>> urlparse.urlunparse(parse)
'https://i.cnblogs.com:80/EditPosts.aspx?opt=1'
>>> urlparse.urlunparse(("https","i.cnblogs.com","/EditPosts.aspx","","opt=1",""))
'https://i.cnblogs.com/EditPosts.aspx?opt=1'

以上这篇基于python(urlparse)模板的使用方法总结就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

您可能有感兴趣的文章
Python自动化运维-使用Python脚本监控华为AR路由器关键路由变化

Python自动化运维-netmiko模块设备自动发现

Python自动化运维—netmiko模块连接并配置华为交换机

Python自动化运维-利用Python-netmiko模块备份设备配置

Python自动化运维-Paramiko模块和堡垒机实战