统一资源定位符 / URL


目录

  1. URL 构成
  2. URL 解析
  3. URL 处理

1 URL构成

统一资源定位符(Uniform Resource Locator) 是对可以从互联网上得到的资源的位置访问方法的一种简洁的表示,是互联网上标准资源的地址。互联网上的每个文件都有一个唯一的URL,它包含的信息指出文件的位置以及浏览器应该怎么处理它。现在已经被万维网联盟编制为互联网标准 RFC1738。

URL的基本格式为,prot_sch://net_loc/path;params?query#frag

各部分组件含义如下,

URL组件

描述

prot_sch

网络协议或下载方案,如HTTP/FTP等

net_loc

服务器所在地,如www.xxx.com/localhost

path

使用斜杠(/)分割的文件CGI路径

params

可选参数

query

连接符&分隔的一系列键值对

frag

指定文档内特定锚的部分

其中net_loc的基本格式为,user:passwd@host:port

各部分组件含义如下,

组件

描述

user

用户名或登录

passwd

用户密码

host

运行Web服务器的计算机名称或地址(必需的)

params

端口号(如果没有则默认80)

在这4个组件中,host是最重要的,port只有在Web服务器运行在非默认端口的情况下才会使用,而用户名和密码只有在FTP连接时才会使用,而即使是FTP大多也都是使用匿名的,此时无需用户名和密码。

2 URL解析

对于URL的解析可以使用urllib中的parse模块来进行,

完整代码

 from urllib import parse

 # urlparse --> urllib.parse since python 3.0

 # urlparse
print(parse.urlparse('http://blog.csdn.net/hxsstar/article/details/17240975'))
# ParseResult(scheme='http', netloc='blog.csdn.net', path='/hxsstar/article/details/17240975', params='', query='', fragment='')
print(parse.urlparse('http://www.python.org/doc/FAQ.html'))
# ParseResult(scheme='http', netloc='www.python.org', path='/FAQ.html', params='', query='', fragment='') # urlunparse
# http://blog.csdn.net/hxsstar/article/details/17240975
print(parse.urlunparse(parse.urlparse('http://blog.csdn.net/hxsstar/article/details/17240975')))
print(parse.urlunparse(parse.ParseResult(scheme='http', netloc='blog.csdn.net', path='/hxsstar/article/details/17240975', params='', query='', fragment=''))) # urljoin
# urljoin will join schema, net_loc and part of path of baseurl, with new url
print(parse.urljoin('http://www.python.org/doc/FAQ.html', 'current/lib/lib.html'))
# http://www.python.org/doc/current/lib/lib.html

分段解释

首先从urllib中导入parse模块,此处需要注意的是,从Python3.0开始,原本的urlparse模块与urlopen等模块重新整合到了urllib中。

 from urllib import parse

 # urlparse --> urllib.parse since python 3.0

使用urlparse函数对一个URL进行解析,最终可以得到结果为ParseResult的实例

 # urlparse
print(parse.urlparse('http://blog.csdn.net/hxsstar/article/details/17240975'))
# ParseResult(scheme='http', netloc='blog.csdn.net', path='/hxsstar/article/details/17240975', params='', query='', fragment='')
print(parse.urlparse('http://www.python.org/doc/FAQ.html'))
# ParseResult(scheme='http', netloc='www.python.org', path='/FAQ.html', params='', query='', fragment='')

使用urlunparse函数则可以逆向上述的过程,将一个ParseResult实例变为URL

 # urlunparse
# http://blog.csdn.net/hxsstar/article/details/17240975
print(parse.urlunparse(parse.urlparse('http://blog.csdn.net/hxsstar/article/details/17240975')))
print(parse.urlunparse(parse.ParseResult(scheme='http', netloc='blog.csdn.net', path='/hxsstar/article/details/17240975', params='', query='', fragment='')))

使用urljoin函数可以处理多个URL,该函数接受两个URL,将其中第一个作为base,保留其schema,net_loc以及path除最终文件名部分的内容,将其与第二个参数进行拼接生成新的URL

 # urljoin
# urljoin will join schema, net_loc and part of path of baseurl, with new url
print(parse.urljoin('http://www.python.org/doc/FAQ.html', 'current/lib/lib.html'))
# http://www.python.org/doc/current/lib/lib.html

3 URL处理

通过URL可以利用urllib模块来进行数据下载等一系列操作,主要利用了url的request模块内的函数来进行,

完整代码

 from urllib import request

 url = 'https://www.baidu.com'

 # urlopen:
# urlopen(urlstr) will open an URL that pointed by urlstr, if no Schema or Schema is 'file' in urlstr, it will open a local file
# it return a file object like open() does
with request.urlopen(url) as f:
print(f) # http.client.HTTPResponse object
re = f.read() # read all bytes
print(re)
re = f.info() # return MIME(Multipurpose Internet Mail Extension)
print(re)
re = f.geturl() # return real URL
print(re) # urlretrieve:
# urlretrieve will download full HTML and save it as a file
# filename -- file save path and file name, default None, and path is AppData/temp
# reporthook -- pass a function to this para, and three para(blocknum, block_size, total_size) will be passed to your function
print(request.urlretrieve(url, filename='baidu_url', reporthook=print)) # quote:
# quote function can encode some symbol that not allowed in URL into %xx
print(request.quote('diss act&cat/sad')) # diss%20act%26cat/sad
print(request.quote('diss act&cat/sad', safe='/&')) # diss%20act&cat/sad # unquote:
print(request.unquote('diss%20act%26cat/sad')) # diss act&cat/sad

分段解释

首先导入request模块,并且定义url参数,接着使用urlopen函数连接URL,若Schema为file或没有Schema,则会打开一个本地文件。该函数返回一个类似于文件的类实例,可通过read()/readline()/readlines()等函数进行数据读取。

 from urllib import request

 url = 'https://www.baidu.com'

 # urlopen:
# urlopen(urlstr) will open an URL that pointed by urlstr, if no Schema or Schema is 'file' in urlstr, it will open a local file
# it return a file object like open() does
with request.urlopen(url) as f:
print(f) # http.client.HTTPResponse object
re = f.read() # read all bytes
print(re)
re = f.info() # return MIME(Multipurpose Internet Mail Extension)
print(re)
re = f.geturl() # return real URL
print(re)

输出结果,其中 3-17 行为MIME信息。

Note: 此处使用 https://www.baidu.com 而不是 http://www.baidu.com,因此当使用urlopen获取网页信息的时候得到的并非原网页的HTML文本,而是一个对https到http的转接,若需要原网页的HTML文本可使用 http://www.baidu.com URL进行连接。

 <http.client.HTTPResponse object at 0x00000000034FEC50>
b'<html>\r\n<head>\r\n\t<script>\r\n\t\tlocation.replace(location.href.replace("https://","http://"));\r\n\t</script>\r\n</head>\r\n<body>\r\n\t<noscript><meta http-equiv="refresh" content="0;url=http://www.baidu.com/"></noscript>\r\n</body>\r\n</html>'
Accept-Ranges: bytes
Cache-Control: no-cache
Content-Length: 227
Content-Type: text/html
Date: Mon, 09 Oct 2017 08:46:05 GMT
Last-Modified: Mon, 25 Sep 2017 03:07:00 GMT
P3p: CP=" OTI DSP COR IVA OUR IND COM "
Pragma: no-cache
Server: BWS/1.1
Set-Cookie: BD_NOT_HTTPS=1; path=/; Max-Age=300
Set-Cookie: BIDUPSID=A73CA416A65961564293CD1641ABCE93; expires=Thu, 31-Dec-37 23:55:55 GMT; max-age=2147483647; path=/; domain=.baidu.com
Set-Cookie: PSTM=1507538765; expires=Thu, 31-Dec-37 23:55:55 GMT; max-age=2147483647; path=/; domain=.baidu.com
Strict-Transport-Security: max-age=0
X-Ua-Compatible: IE=Edge,chrome=1
Connection: close https://www.baidu.com

当我们需要保存读取到的HTML文件时,可以使用urlretrieve()函数进行,向该函数传入目标url,保存的文件名,以及一个hook函数,保存文件的过程中会向hook函数中传入3个参数,分别是目前读入块数,块的字节数,文件的总字节数。可以利用此信息确定读取进度。最终urlretrieve函数返回一个二元元组,包括存储数据的文件名,以及含有文件头信息的Message类。

 # urlretrieve:
# urlretrieve will download full HTML and save it as a file
# filename -- file save path and file name, default None, and path is AppData/temp
# reporthook -- pass a function to this para, and three para(blocknum, block_size, total_size) will be passed to your function
print(request.urlretrieve(url, filename='baidu_url', reporthook=print))

以下为输出结果,

0 8192 227
1 8192 227
('baidu_url', <http.client.HTTPMessage object at 0x00000000035D38D0>)

最后是使用quote和unquote函数对URL进行转换,在URL中存在许多不支持的字符,例如空格等,可将其转换为%xx,xx表示该字符的十六进制ASCII码,使用quote和unquote函数可以在两者之间进行切换,同时quote函数还支持safe参数,选择不需要转换的字符进行保留,其默认值为‘/’,类似的还有quote_plus/unquote_plus函数(转换+号)。

 # quote:
# quote function can encode some symbol that not allowed in URL into %xx
print(request.quote('diss act&cat/sad')) # diss%20act%26cat/sad
print(request.quote('diss act&cat/sad', safe='/&')) # diss%20act&cat/sad # unquote:
print(request.unquote('diss%20act%26cat/sad')) # diss act&cat/sad

Python的Web编程[0] -> Web客户端[0] -> 统一资源定位符 URL的更多相关文章

  1. 161125、Java网络编程之统一资源定位符URL

    统一资源定位符URL(Uniform Resource Locator)是www客户机访问Internet时用来标识资源的名字和地址.超文本链路由统一资源定位符URL维持.URL的格式是: <M ...

  2. Java知多少(104)网络编程之统一资源定位符URL

    统一资源定位符URL(Uniform Resource Locator)是www客户机访问Internet时用来标识资源的名字和地址.超文本链路由统一资源定位符URL维持.URL的格式是: <M ...

  3. Python的Web编程[1] -> Web服务器[0] -> Web 服务器与 CGI / WSGI

    Web服务器 / Web Server 对于Web来说,需要建立一个Web服务器,必须建立一个基本的服务器和一个处理程序, 基本服务器的主要作用是,在客户端和服务器端完成必要的HTTP交互, 处理程序 ...

  4. Python的网络编程[2] -> TFTP 协议[0] -> TFTP 的基本理论

    TFTP 的基本理论 目录 通信流程 数据报文格式 传输终结 异常处理 数据丢失和超时 TFTP(Trivial File Transfer Protocol,简单文件传输协议)是UDP协议族中的一个 ...

  5. Python的网络编程[3] -> BOOTP 协议[0] -> BOOTP 的基本理论

    BOOTP协议 / BOOTP Protocol 目录 基本理论 BOOTP 与 DHCP 通信流程 数据报文格式 报文加解码实现 1. 基本理论 / Basic Theory BOOTP(Boots ...

  6. Python的Web编程[2] -> WebService技术[0] -> 利用 Python 调用 WebService 接口

    WebService技术 / WebService Technology 1 关于webservice / Constants WebService是一种跨编程语言和跨操作系统平台的远程调用技术. W ...

  7. Python的网络编程[1] -> FTP 协议[0] -> FTP 的基本理论

    FTP协议 / FTP Protocol FTP全称为File Transfer Protocol(文件传输协议),常用于Internet上控制文件的双向传输,常用的操作有上传和下载.基于TCP/IP ...

  8. Python的网络编程[4] -> DHCP 协议[0] -> DHCP 的基本理论

    DHCP协议 / DHCP Protocol 目录 DHCP 基本理论 DHCP 通信流程 DHCP 完整报文 DHCP 的 Optional 字段 DHCP 的报文类型 1 DHCP 基本理论 DH ...

  9. 【python】网络编程-SocketServer 实现客户端与服务器间非阻塞通信

    利用SocketServer模块来实现网络客户端与服务器并发连接非阻塞通信.首先,先了解下SocketServer模块中可供使用的类:BaseServer:包含服务器的核心功能与混合(mix-in)类 ...

随机推荐

  1. 《Cracking the Coding Interview》——第18章:难题——题目12

    2014-04-29 04:36 题目:最大子数组和的二位扩展:最大子矩阵和. 解法:一个维度上进行枚举,复杂度O(n^2):另一个维度执行最大子数组和算法,复杂度O(n).总体时间复杂度为O(n^3 ...

  2. UnitOfWork知多少 【转】

    原文链接:https://www.cnblogs.com/sheng-jie/p/7416302.html 1. 引言 Maintains a list of objects affected by ...

  3. 聊聊、SpringBoot 上传文件大小

    #2.0#spring.servlet.multipart.max-file-size=10Mb#spring.servlet.multipart.max-request-size=10Mb #1.3 ...

  4. PBFT性能会下降? 各种算法的对比。

    PBFT协议在超过100个节点的时候性能会下降 作者:maxdeath 链接:https://www.zhihu.com/question/60058591/answer/173970031 首先要搞 ...

  5. 【bzoj4884】[Lydsy2017年5月月赛]太空猫 dp

    原文地址:http://www.cnblogs.com/GXZlegend/p/6825431.html 题目描述 太空猫(SpaceCat)是一款画面精致.玩法有趣的休闲游戏,你需要控制一只坐在迷你 ...

  6. hdu 1211 RSA (逆元)

    RSA Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)Total Submiss ...

  7. [hdu6437]Problem L. Videos

    题目大意:有$n$个小时,有$m$个节目(每种节目都有类型$0/1$),有$k$个人,一个人连续看相同类型的节目会扣$w$快乐值. 每一种节目有都一个播放区间$[l,r]$.每个人同一时间只能看一个节 ...

  8. P1494 [国家集训队]小Z的袜子/莫队学习笔记(误

    P1494 [国家集训队]小Z的袜子 题目描述 作为一个生活散漫的人,小\(Z\)每天早上都要耗费很久从一堆五颜六色的袜子中找出一双来穿.终于有一天,小\(Z\)再也无法忍受这恼人的找袜子过程,于是他 ...

  9. ServletContext结合Servlet接口中的init()方法和destroy()方法的运用----网站计数器

    我们一般知道Servlet接口中的init()方法在tomcat启动时调用,destroy()方法在tomcat关闭时调用.那么这两个方法到底在实际开发中有什么作用呢?这就是这个随笔主要讲的内容. 思 ...

  10. Python实现求矩阵路径最小和,使用动态规划

    题目: 给定一些NxN的矩阵,对于任意的路线,定义其[和]为其线路上所有节点的数字的和,计算从左上角到右下角的路线和最小值.每条路线只能从某一点到其周围(上下左右)的点,不可斜行.例如: 4,6 2, ...