1. 程式人生 > >urllib.parse.parse_qsl 的一個小問題

urllib.parse.parse_qsl 的一個小問題

def 不知道 lose urllib and intended indicate val percent

最近在使用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 的一個小問題