【问题标题】:UnicodeWarning: Unicode equal comparison failed to convert both arguments to UnicodeUnicodeWarning:Unicode 相等比较未能将两个参数都转换为 Unicode
【发布时间】:2015-01-29 13:11:46
【问题描述】:

我知道很多人以前遇到过这个错误,但我找不到解决我的问题的方法。

我有一个要规范化的 URL:

url = u"http://www.dgzfp.de/Dienste/Fachbeitr%C3%A4ge.aspx?EntryId=267&Page=5"
scheme, host_port, path, query, fragment = urlsplit(url)
path = urllib.unquote(path)
path = urllib.quote(path,safe="%/")

这会给出一条错误消息:

/usr/lib64/python2.6/urllib.py:1236: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
  res = map(safe_map.__getitem__, s)
Traceback (most recent call last):
  File "url_normalization.py", line 246, in <module>
    logging.info(get_canonical_url(url))
  File "url_normalization.py", line 102, in get_canonical_url
    path = urllib.quote(path,safe="%/")
  File "/usr/lib64/python2.6/urllib.py", line 1236, in quote
    res = map(safe_map.__getitem__, s)
KeyError: u'\xc3'

我尝试从 URL 字符串中删除 unicode 指示符“u”,但没有收到错误消息。但是我怎样才能自动摆脱 unicode,因为我直接从数据库中读取它。

【问题讨论】:

标签: python unicode


【解决方案1】:

urllib.quote() 无法正确解析 Unicode。为了解决这个问题,您可以在读取 url 时调用.encode() 方法(或从数据库中读取的变量)。所以运行url = url.encode('utf-8')。有了这个,你得到:

import urllib
import urlparse
from urlparse import urlsplit

url = u"http://www.dgzfp.de/Dienste/Fachbeitr%C3%A4ge.aspx?EntryId=267&Page=5"
url = url.encode('utf-8')
scheme, host_port, path, query, fragment = urlsplit(url)
path = urllib.unquote(path)
path = urllib.quote(path,safe="%/")

然后path 变量的输出将是:

>>> path
'/Dienste/Fachbeitr%C3%A4ge.aspx'

这行得通吗?

【讨论】:

  • 这对我有用。谢谢你。其实我在编码前后打印了type(url),发现编码前是,编码后是
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-02
  • 1970-01-01
  • 1970-01-01
  • 2012-08-20
相关资源
最近更新 更多