zoukankan      html  css  js  c++  java
  • urllib.urlencode() 无法encode中文, UnicodeEncodeError

    urllib.urlencode() 无法encode中文, UnicodeEncodeError, 具体错误内容如下:
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib.py", line 1326, in urlencode
    v = quote_plus(str(v))

    UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128)

    引发此错误代码:

    #encoding=utf-8
    import urllib
    url_dict = {"name": u"张三哥", "age": 20}
    print "http://xxx.yyy.com?%s" % urllib.urlencode(url_dict)
    

    函数urlencode不会改变传入参数的原始编码,也就是说需要在调用之前将post或get参数的编码调整好,采用encode方法:

    #encoding=utf-8
    import urllib
    url_dict = {"name": u"张三哥".encode('gb2312'), "age": 20}
    print "http://xxx.yyy.com?%s" % urllib.urlencode(url_dict)
    

    Result:

    http://xxx.yyy.com?age=20&name=%D5%C5%C8%FD%B8%E7
    

    用gb2312编码是可以的, 如上所示, 如果我用utf-8来encode呢? 其实也是可以的, 主要看在哪里使用, 注: baidu使用的是gb2312编码,google使用的是utf8编码,两个站点提交到URL中的中文参数的urlencode值是不一样

    参考资料:

    参考一: python urlencode编码

    参考二: python编码转换

  • 相关阅读:
    制作dos启动u盘
    服务器之ECC报错检查
    shc 对 Linux shell 脚本加密.
    Linux
    windows查看端口占用
    python语言
    AppScan9.0安装破解
    局域网灰色设置解除
    shell脚本
    nginx安装
  • 原文地址:https://www.cnblogs.com/AmilyWilly/p/6438547.html
Copyright © 2011-2022 走看看