统一资源定位符 / 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. Object Pascal中文手册 经典教程

    Object Pascal 参考手册 (Ver 0.1)ezdelphi@hotmail.com OverviewOverview(概述)Using object pascal(使用 object p ...

  2. node express 登录拦截器 request接口请求

    1.拦截器 拦截器可以根据需要 做权限拦截 登录只是权限的一种, 思路是req.session.user判断用户session是否存在,是否是需要拦截的地址, 如果是就跳转登录页,或其他页, 如果非需 ...

  3. Windows下安装PHP及开发环境配置

    一.Apache 因为Apache官网只提供源代码,如果要使用必须得自己编译,这里我选择第三方安装包Apache Lounge. 1. 进入Apachelounge官方下载地址:http://www. ...

  4. 抓包工具 - Fiddler - (一)

    <转载于 miantest> Fiddler基础知识 Fiddler是强大的抓包工具,它的原理是以web代理服务器的形式进行工作的,使用的代理地址是:127.0.0.1,端口默认为8888 ...

  5. 你的第一个自动化测试:Appium 自动化测试

    前言: 这是让你掌握 App 自动化的文章 一.前期准备 本文版权归作者和博客园共有,原创作者:http://www.cnblogs.com/BenLam,未经作者同意必须在文章页面给出原文连接. 1 ...

  6. springboot生成表结构

    https://blog.csdn.net/yalishadaa/article/details/59656332

  7. Wordpress 为用户或角色 role 添加 capabilities(权限)

    首先查看角色具有哪些权限: $admin_role_set = get_role( 'administrator' )->capabilities; $author_role_set = get ...

  8. Wordpress 后台文章编辑区添加模板选择功能

    功能:后台编辑文章时,可以选择文章使用的模板,效果如下图: 操作步骤: <?php /** * Template Name: kbsingle full * Add by Ryan 3/18/2 ...

  9. 1106 Lowest Price in Supply Chain (25 分)(树的遍历)

    求叶子结点处能活得最低价格以及能提供最低价格的叶子结点的个数 #include<bits/stdc++.h> using namespace std; ; vector<int> ...

  10. 批量部署ssh免密登陆

    #!/bin/bash#set -xservers="10.254.192.xx10.254.192.xx10.254.192.xx"passwd="xxxxxxxx&q ...