最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【已解决】Python中给url中的字符串进行encode编码

Python crifan 1501浏览 0评论
折腾:
【已解决】后台用Flask封装百度的语音合成功能对外提供REST API接口
期间,需要对于输入的字符串,比如:
as a book-collector, i have the story you just want to listen!
进行url的encode
注意到:一般来说,去encode编码字符串,用于url中的话,encoding编码类型,都是utf-8
比如:
url解码
UrlEncode编码/UrlDecode解码 – 站长工具
中上述字符串进行utf-8编码后是:
as+a+book-collector%2c+i+have+the+story+you+just+want+to+listen!
然后此处要去实现:
python代码中的url的encode
python url encode
python中的urlencode与urldecode – CSDN博客
quote(),unquote(),urlencode()编码解码_urllib网络编程库_python学习_编程语言学习__www.iteedu.com
http://www.iteedu.com/plang/python/urllib/quote.php
url encoding – How to urlencode a querystring in Python? – Stack Overflow
How to percent-encode URL parameters in Python? – Stack Overflow
Python urllib模块的URL编码解码功能 — 简明现代魔法
21.8. urllib.parse — Parse URLs into components — Python 3.6.5 documentation
【总结】
最后搞清楚了Python 2和Python 3中的url的encode和quote 和quote_plus的区别:
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Author: Crifan Li
# Date: 20180511
# Function: Demo url encode and quote for Python 2.x and 3.x

import sys

curPythonVersion = sys.version
print("curPythonVersion=%s" % curPythonVersion)
# '2.7.10 (default, Oct  6 2017, 22:29:07)
# [GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.31)]'
#
# '3.6.4 (default, Mar 22 2018, 13:54:22)
# [GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.39.2)]'
curPythonVersionInfo = sys.version_info
# print("curPythonVersionInfo=%s" % curPythonVersionInfo)
# sys.version_info(major=2, minor=7, micro=10, releaselevel='final', serial=0)
# sys.version_info(major=3, minor=6, micro=4, releaselevel='final', serial=0)
curPythonVersionMajor = curPythonVersionInfo.major

if curPythonVersionMajor == 2:
    print("Current is Python 2")
    # https://docs.python.org/2/library/urllib.html
    from urllib import urlencode, quote, quote_plus
elif curPythonVersionMajor == 3:
    print("Current is Python 3")
    # https://docs.python.org/3/library/urllib.parse.html
    from urllib.parse import urlencode, quote, quote_plus

forUrlEncodeDict = {"name": "Crifan Li"}  # a dict of keys and values
urlEncodedStrFromDict = urlencode(forUrlEncodeDict)  # => key=quote_plus value => 'name=Crifan+Li'
print("urlEncodedStrFromDict==%s" % (urlEncodedStrFromDict))

strForUrlQuote = "normal query string in http get"
urlQuoteStr = quote(strForUrlQuote) #space quoted to %20 => 'normal%20query%20string%20in%20http%20get'
urlQuotePlusStr = quote_plus(strForUrlQuote) #space quoted to + => 'normal+query+string+in+http+get'
print("urlQuoteStr=%s,urlQuotePlusStr=%s" % (urlQuoteStr, urlQuotePlusStr))

转载请注明:在路上 » 【已解决】Python中给url中的字符串进行encode编码

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
82 queries in 0.179 seconds, using 22.08MB memory