Python的Web编程[0] -> Web客户端[0] -> 统一资源定位符 URL
统一资源定位符 / 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的更多相关文章
- 161125、Java网络编程之统一资源定位符URL
统一资源定位符URL(Uniform Resource Locator)是www客户机访问Internet时用来标识资源的名字和地址.超文本链路由统一资源定位符URL维持.URL的格式是: <M ...
- Java知多少(104)网络编程之统一资源定位符URL
统一资源定位符URL(Uniform Resource Locator)是www客户机访问Internet时用来标识资源的名字和地址.超文本链路由统一资源定位符URL维持.URL的格式是: <M ...
- Python的Web编程[1] -> Web服务器[0] -> Web 服务器与 CGI / WSGI
Web服务器 / Web Server 对于Web来说,需要建立一个Web服务器,必须建立一个基本的服务器和一个处理程序, 基本服务器的主要作用是,在客户端和服务器端完成必要的HTTP交互, 处理程序 ...
- Python的网络编程[2] -> TFTP 协议[0] -> TFTP 的基本理论
TFTP 的基本理论 目录 通信流程 数据报文格式 传输终结 异常处理 数据丢失和超时 TFTP(Trivial File Transfer Protocol,简单文件传输协议)是UDP协议族中的一个 ...
- Python的网络编程[3] -> BOOTP 协议[0] -> BOOTP 的基本理论
BOOTP协议 / BOOTP Protocol 目录 基本理论 BOOTP 与 DHCP 通信流程 数据报文格式 报文加解码实现 1. 基本理论 / Basic Theory BOOTP(Boots ...
- Python的Web编程[2] -> WebService技术[0] -> 利用 Python 调用 WebService 接口
WebService技术 / WebService Technology 1 关于webservice / Constants WebService是一种跨编程语言和跨操作系统平台的远程调用技术. W ...
- Python的网络编程[1] -> FTP 协议[0] -> FTP 的基本理论
FTP协议 / FTP Protocol FTP全称为File Transfer Protocol(文件传输协议),常用于Internet上控制文件的双向传输,常用的操作有上传和下载.基于TCP/IP ...
- Python的网络编程[4] -> DHCP 协议[0] -> DHCP 的基本理论
DHCP协议 / DHCP Protocol 目录 DHCP 基本理论 DHCP 通信流程 DHCP 完整报文 DHCP 的 Optional 字段 DHCP 的报文类型 1 DHCP 基本理论 DH ...
- 【python】网络编程-SocketServer 实现客户端与服务器间非阻塞通信
利用SocketServer模块来实现网络客户端与服务器并发连接非阻塞通信.首先,先了解下SocketServer模块中可供使用的类:BaseServer:包含服务器的核心功能与混合(mix-in)类 ...
随机推荐
- 【Perceptron Learning Algorithm】林轩田机器学习基石
直接跳过第一讲.从第二讲Perceptron开始,记录这一讲中几个印象深的点: 1. 之前自己的直觉一直对这种图理解的不好,老按照x.y去理解. a) 这种图的每个坐标代表的是features:fea ...
- docker部署思路
1.docker安装2.拉取centos镜像或者Ubuntu镜像 看你用哪个3.使用镜像,run出来一个容器A4.进入容器A,安装uwsgi,把Django部署在下面5.在启动脚本中配置开机自启动脚本 ...
- Python全栈工程师(每周总结:1)
ParisGabriel python今年9月份将被国家纳入计算机二级资格证 先学就是鼻祖 几年后你就是大牛 Python人工智能从入门到精通 week summer: ...
- pom中的resources设置
Maven项目中一般都会把配置文件放到src/main/resources目录下,有时为了满足多个环境打包发布,可能会创建一些自定义目录来放置各环境的配置文件,如:src/main/profile/d ...
- Linux下性能测量和调试诊断工具Systemtap
一.简介 SystemTap是一个诊断Linux系统性能或功能问题的开源软件.它使得对运行时的Linux系统进行诊断调式变得更容易.更简单.有了它,开发者或调试人员不再需要重编译.安装新内核.重启动等 ...
- 乌龟git
相关操作 链接:http://www.cnblogs.com/hbujt/p/5554038.html 避免乌龟每次输入账户密码 链接:http://www.cnblogs.com/bldf/p/60 ...
- 关闭vscode打开新文件自动关闭预览文件功能
经常碰到这个问题,我打开文件就是有用的,每次给我自动关闭了我还得去打开. 当然这个问题可以双击文件,接触那个文件的预览状态就可以解决了.不过还有一个更懒的方法,直接修改vscode配置就好了. // ...
- inux下设置mysql数据库字符集utf8
mysql中文乱码解决方法:将mysql数据库编码统一utf8 查看数据库编码: ? 1 <span style="font-size: 16px;"><stro ...
- 自定义View基础 (1)
前言 自定义View原理是Android开发者必须了解的基础: 在了解自定义View之前,你需要有一定的知识储备: 本文将全面解析关于自定义View中的所有知识基础. 目录 目录 1. View的分类 ...
- glance总结
Openstack将glance独立出来的一个原因是尽可能将镜像存储至多种存储上,由glance提供一个完整的适配框架.现在支持亚马逊对象存储S3.openstack自有的swift对象存储,以及常用 ...