我是 Python 和 Scrapy 的新手,我正在尝试测试一个字符串(使用 xpath 选择器提取)是否包含英镑符号(英国货币 - £)。
在源文件的顶部我指定了编码:
# -*- coding: latin-1 -*-
我正在执行此测试:
if '£' in price:
...
但是我收到错误 exceptions.UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2。
如果我将测试更改为
price = price.encode('utf-8')
if '£' in price:
...
它有效。有人可以解释为什么 price.encode() 调用是必要的,我知道 Scrapy 无论如何都会返回 unicode 字符串。非常感谢
请您参考如下方法:
# these have different types:
if some_string in some_unicode_object
这样做相当于写:
# convert the first argument so we can do the `in`
if some_string.decode('ascii') in some_unicode_object
所以在你的例子中:
if '£' in price:
# ^string ^unicode
您正在调用 '£'.encode('ascii'),但它失败了,因为它不是 ASCII 字节串。
更好的写法是:
if u'£' in price:
或者,您可能想写 from __future__ import unicode_literals .
