python 中 quote 与 urlencode 的用法与区别

quote:

  • quote 对非ASCII编码的字符进行编码,默认进行UTF-8编码,不对“/”进行编码
  • 一般对请求url路径中非ASCII编码的字符(string)进行编码
# quote 函数在 urllib.parse中:
function quote in module urllib.parse:
# quote 函数的定义
quote(string, safe='/', encoding=None, errors=None)
# url 中保留的字符:
    reserved    = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" |
                  "$" | ","
  • url 请求链接不能包含非ASCII编码的字符,非ASCII编码的字符被认为是不安全的,所以进行编码。
>>> from urllib.parse import quote
>>> url = "http://www.baidu.com/?name=jack&age=29"
>>> quote(url)
'http%3A//www.baidu.com/%3Fname%3Djack%26age%3D29'
>>> quote(url,safe=";/?:@&=+$,")
'http://www.baidu.com/?name=jack&age=29'
>>> from urllib.parse import quote
>>> url = "http://www.baidu.com/"
>>> qeury = "python入门到精通?数量=3"
>>> quote(qeury,safe=";/?:@&=+$,")
'python%E5%85%A5%E9%97%A8%E5%88%B0%E7%B2%BE%E9%80%9A?%E6%95%B0%E9%87%8F=3'
>>> url = url +quote(qeury,safe=";/?:@&=+$,")
>>> url
'http://www.baidu.com/python%E5%85%A5%E9%97%A8%E5%88%B0%E7%B2%BE%E9%80%9A?%E6%95%B0%E9%87%8F=3'
>>>
  1. quote对string进行编码,默认 encoding=‘utf-8’ (characters are encoded with UTF-8),errors=‘strict’(如果不能对string进行编码,rasie 引发一个 UnicodeEncodeErrort 错误)。
  2. safe = “/”,说明“/”是安全的,不用进行编码.。
  3. url 中保留的字符:在url 中都认为是安全的可以不进行编码,safe包含的字符都不会被编码。

urlencode:

  • urlencode 对字典或由两元素元组组成的列表进行码编码,将其转换为符合url规范的查询字符串
>>> from urllib.parse import urlencode
>>> urlencode([("number",1)])
'number=1'
>>> urlencode([("数量",1),("number",1)])
'%E6%95%B0%E9%87%8F=1&number=1'
>>>
>>> urlencode({"数量": 1, "number": 1})
'%E6%95%B0%E9%87%8F=1&number=1'
  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值