Python urllib模块的URL编码解码功能

参考:http://www.nowamagic.net/academy/detail/1302863

我们知道,url 中是不能出现一些特殊的符号的,有些符号有特殊的用途。比如以 get 方式提交数据的时候,会在 url 中添加 key=value 这样的字符串,所以在 value 中是不允许有 '=',因此要对其进行编码;与此同时服务器接收到这些参数的时候,要进行解码,还原成原始的数据。这个时候,这些辅助方法会很有用:

  • urllib.quote(string[, safe]):对字符串进行编码。参数 safe 指定了不需要编码的字符;
  • urllib.unquote(string) :对字符串进行解码;
  • urllib.quote_plus(string [ , safe ] ) :与 urllib.quote 类似,但这个方法用'+'来替换' ',而 quote 用'%20'来代替' '
  • urllib.unquote_plus(string ) :对字符串进行解码;
  • urllib.urlencode(query[, doseq]):将dict或者包含两个元素的元组列表转换成url参数。例如 字典{'name': 'dark-bull', 'age': 200}将被转换为"name=dark-bull&age=200"
  • urllib.pathname2url(path):将本地路径转换成 url 路径;
  • urllib.url2pathname(path):将url路径转换成本地路径;

我们接下来运行一下下面的脚本来加深理解。

01 import urllib
02 data = 'name = ~nowamagic+5'
03    
04 data1 = urllib.quote(data)
05 print data1 # result: name%20%3D%20%7Enowamagic%2B5
06 print urllib.unquote(data1) # name = ~nowamagic+5
07    
08 data2 = urllib.quote_plus(data)
09 print data2 # result: name+%3D+%7Enowamagic%2B5
10 print urllib.unquote_plus(data2)    # name = ~nowamagic+5
11    
12 data3 = urllib.urlencode({ 'name''nowamagic-gonn''age'200 })
13 print data3 # result: age=200&name=nowamagic-gonn
14    
15 data4 = urllib.pathname2url(r'd:/a/b/c/23.php')
16 print data4 # result: ///D://a/b/c/23.php
17 print urllib.url2pathname(data4)    # result: D:/a/b/c/23.php

在 Python Shell 里执行的具体情况为:

01 Python 2.7.5 (default, May 15 201322:44:16) [MSC v.1500 64 bit (AMD64)] on win32
02 Type "copyright""credits" or "license()" for more information.
03 >>> import urllib
04 >>> data = 'name = ~nowamagic+5'
05 >>> data1 = urllib.quote(data)
06 >>> print data1
07 name%20%3D%20%7Enowamagic%2B5
08 >>> print urllib.unquote(data1)
09 name = ~nowamagic+5
10 >>> data2 = urllib.quote_plus(data)
11 >>> print data2
12 name+%3D+%7Enowamagic%2B5
13 >>> print urllib.unquote_plus(data2)
14 name = ~nowamagic+5
15 >>> data3 = urllib.urlencode({ 'name''nowamagic-gonn''age'200 })
16 >>> print data3
17 age=200&name=nowamagic-gonn
18 >>> data4 = urllib.pathname2url(r'd:/a/b/c/23.php')
19 >>> print data4
20 ///D://a/b/c/23.php
21 >>> print urllib.url2pathname(data4)
22 D:\a\b\c\23.php

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值