zoukankan      html  css  js  c++  java
  • Python的Web编程[0] -> Web客户端[0] -> 统一资源定位符 URL

    统一资源定位符 / 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模块来进行,

    完整代码

     1 from urllib import parse
     2 
     3 # urlparse --> urllib.parse since python 3.0
     4 
     5 # urlparse
     6 print(parse.urlparse('http://blog.csdn.net/hxsstar/article/details/17240975'))
     7 # ParseResult(scheme='http', netloc='blog.csdn.net', path='/hxsstar/article/details/17240975', params='', query='', fragment='')
     8 print(parse.urlparse('http://www.python.org/doc/FAQ.html'))
     9 # ParseResult(scheme='http', netloc='www.python.org', path='/FAQ.html', params='', query='', fragment='')
    10 
    11 # urlunparse
    12 # http://blog.csdn.net/hxsstar/article/details/17240975
    13 print(parse.urlunparse(parse.urlparse('http://blog.csdn.net/hxsstar/article/details/17240975')))
    14 print(parse.urlunparse(parse.ParseResult(scheme='http', netloc='blog.csdn.net', path='/hxsstar/article/details/17240975', params='', query='', fragment='')))
    15 
    16 # urljoin
    17 # urljoin will join schema, net_loc and part of path of baseurl, with new url
    18 print(parse.urljoin('http://www.python.org/doc/FAQ.html', 'current/lib/lib.html'))
    19 # http://www.python.org/doc/current/lib/lib.html
    View Code

    分段解释

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

    1 from urllib import parse
    2 
    3 # urlparse --> urllib.parse since python 3.0

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

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

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

    1 # urlunparse
    2 # http://blog.csdn.net/hxsstar/article/details/17240975
    3 print(parse.urlunparse(parse.urlparse('http://blog.csdn.net/hxsstar/article/details/17240975')))
    4 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

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

    3 URL处理

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

    完整代码

     1 from urllib import request
     2 
     3 url = 'https://www.baidu.com'
     4 
     5 # urlopen: 
     6 # 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
     7 # it return a file object like open() does
     8 with request.urlopen(url) as f:
     9     print(f)    # http.client.HTTPResponse object
    10     re = f.read()   # read all bytes
    11     print(re)
    12     re = f.info()   # return MIME(Multipurpose Internet Mail Extension)
    13     print(re)   
    14     re = f.geturl() # return real URL
    15     print(re)   
    16 
    17 # urlretrieve: 
    18 # urlretrieve will download full HTML and save it as a file
    19 # filename -- file save path and file name, default None, and path is AppData/temp
    20 # reporthook -- pass a function to this para, and three para(blocknum, block_size, total_size) will be passed to your function
    21 print(request.urlretrieve(url, filename='baidu_url', reporthook=print))
    22 
    23 # quote:
    24 # quote function can encode some symbol that not allowed in URL into %xx
    25 print(request.quote('diss act&cat/sad')) # diss%20act%26cat/sad 
    26 print(request.quote('diss act&cat/sad', safe='/&')) # diss%20act&cat/sad 
    27 
    28 # unquote:
    29 print(request.unquote('diss%20act%26cat/sad')) # diss act&cat/sad
    View Code

    分段解释

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

     1 from urllib import request
     2 
     3 url = 'https://www.baidu.com'
     4 
     5 # urlopen: 
     6 # 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
     7 # it return a file object like open() does
     8 with request.urlopen(url) as f:
     9     print(f)    # http.client.HTTPResponse object
    10     re = f.read()   # read all bytes
    11     print(re)
    12     re = f.info()   # return MIME(Multipurpose Internet Mail Extension)
    13     print(re)   
    14     re = f.geturl() # return real URL
    15     print(re)   

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

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

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

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

    1 # urlretrieve: 
    2 # urlretrieve will download full HTML and save it as a file
    3 # filename -- file save path and file name, default None, and path is AppData/temp
    4 # reporthook -- pass a function to this para, and three para(blocknum, block_size, total_size) will be passed to your function
    5 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函数(转换+号)。

    1 # quote:
    2 # quote function can encode some symbol that not allowed in URL into %xx
    3 print(request.quote('diss act&cat/sad')) # diss%20act%26cat/sad 
    4 print(request.quote('diss act&cat/sad', safe='/&')) # diss%20act&cat/sad 
    5 
    6 # unquote:
    7 print(request.unquote('diss%20act%26cat/sad')) # diss act&cat/sad
  • 相关阅读:
    默认开机启动;通过Broadcastreceiver广播监听开机启动,实现"没有activity"的自启服务或者自启应用程序。
    android中一个应用程序启动另外一个应用程序,并传递数据。
    调用远程服务里的方法service,进程间通信adil的学习
    android学习之Service的笔记,里面service里有监听用户通话状态的实例
    modelform的操作以及验证
    Django中提供的6种缓存方式
    csrf 跨站请求伪造相关以及django的中间件
    cookies和session
    splinter
    cookie实现用户登录验证
  • 原文地址:https://www.cnblogs.com/stacklike/p/8244807.html
Copyright © 2011-2022 走看看