最近在使用urllib时发现的一个问题,记录一下。

首先请分别执行下面这两句代码:
  1、"你好".encode("utf8").decode("gbk")
  2、"你".encode("utf8").decode("gbk") 结果:
  1、正常运行 只是输出是乱码
  2 报错 编码解析错误 具体原因就不分析了,下面说一下造成的问题 在urllib.parse.parse_qsl函数中
def parse_qsl(qs, keep_blank_values=False, strict_parsing=False,
encoding='utf-8', errors='replace'):
"""Parse a query given as a string argument. Arguments: qs: percent-encoded query string to be parsed keep_blank_values: flag indicating whether blank values in
percent-encoded queries should be treated as blank strings.
A true value indicates that blanks should be retained as blank
strings. The default false value indicates that blank values
are to be ignored and treated as if they were not included. strict_parsing: flag indicating what to do with parsing errors. If
false (the default), errors are silently ignored. If true,
errors raise a ValueError exception. encoding and errors: specify how to decode percent-encoded sequences
into Unicode characters, as accepted by the bytes.decode() method. Returns a list, as G-d intended.
"""
qs, _coerce_result = _coerce_args(qs)
pairs = [s2 for s1 in qs.split('&') for s2 in s1.split(';')]
r = []
for name_value in pairs:
if not name_value and not strict_parsing:
continue
nv = name_value.split('=', 1)
if len(nv) != 2:
if strict_parsing:
raise ValueError("bad query field: %r" % (name_value,))
# Handle case of a control-name with no equal sign
if keep_blank_values:
nv.append('')
else:
continue
if len(nv[1]) or keep_blank_values:
name = nv[0].replace('+', ' ')
name = unquote(name, encoding=encoding, errors=errors)
name = _coerce_result(name)
value = nv[1].replace('+', ' ')
value = unquote(value, encoding=encoding, errors=errors)
value = _coerce_result(value)
r.append((name, value))
return r
当解析出url中的参数后,会使用urllib.parse.unquote对参数名称和值分别做一下URL编码转换,于是问题就出现了
根据上面的示例代码,偶数个中文编解码是不会报错的(在编码错误的情况下),下面分情况讨论:
1、如果你很明确知道url参数中的编码方式是utf8或者gbk时,获取到的query中的value没有问题,你可以执行一个固定的编码。
2、如果你的输入是不固定的,混杂着各种编码的时候,就蛋疼了,因为不会抛出异常,所以你只能发现结果中出现了各种乱码,却不知道问题出在那里 貌似这并不是一个问题。。。 只是在某些情况下用起来不太方便,例如:
  当你想把url中某些参数去掉,然后把剩下的拼接起来的时候还要重新quote一下

最新文章

  1. webpack配置备份
  2. 激活windows10 LTSB 2016
  3. 综合使用spring cloud技术实现微服务应用
  4. Linux内核知识
  5. ios基础之入门(一)
  6. 设置dom元素可拖动,支持ie5+
  7. <%# Convert.ToDecimal(Eval("IMLognum")).ToString("F0") %>
  8. CRF++中文分词使用指南
  9. #include <thread>
  10. bzoj1562【Noi2009】变换序列
  11. svn检出服务器项目中出现的could not connect to server
  12. 两个js冲突怎么解决?试试这四个方法
  13. js基础-数组及数据类型
  14. yii gii配置ip限制使用gii
  15. Java与go哪个更适合后端开发呢?哪个更适合新手呢?
  16. 【转】Linux 高级的视角来查看Linux引导过程
  17. 基于Redis分布式锁(获取锁及解锁)
  18. maven错误The JAVA_HOME environment variable is not defined correctly
  19. com.alibaba.druid检测排查数据库连接数不释放定位代码
  20. 不得不知的Excel技巧

热门文章

  1. TF30063:没有访问xxx的权限 vs2017
  2. Oracle_SQL(2) 分组与聚合函数
  3. git bug修复
  4. Liunx 重定向,管道符(转)
  5. DOM-设置样式心得
  6. hdu 5461(2015沈阳网赛 简单暴力) Largest Point
  7. 杭电1518 Square(构成正方形) 搜索
  8. 网络编程 tcp(一)
  9. [Python] 代码中有中文注释会报错
  10. Python之路(第七篇)Python作用域、匿名函数、函数式编程、map函数、filter函数、reduce函数