分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 技术分享

urllib.parse.parse_qsl 的一个小问题

发布时间:2023-09-06 02:21责任编辑:蔡小小关键词:url
最近在使用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
View Code
当解析出url中的参数后,会使用urllib.parse.unquote对参数名称和值分别做一下URL编码转换,于是问题就出现了
根据上面的示例代码,偶数个中文编解码是不会报错的(在编码错误的情况下),下面分情况讨论:
1、如果你很明确知道url参数中的编码方式是utf8或者gbk时,获取到的query中的value没有问题,你可以执行一个固定的编码。
2、如果你的输入是不固定的,混杂着各种编码的时候,就蛋疼了,因为不会抛出异常,所以你只能发现结果中出现了各种乱码,却不知道问题出在那里

貌似这并不是一个问题。。。

只是在某些情况下用起来不太方便,例如:
  当你想把url中某些参数去掉,然后把剩下的拼接起来的时候还要重新quote一下


urllib.parse.parse_qsl 的一个小问题

原文地址:https://www.cnblogs.com/dyfblog/p/9089542.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved