打印到命令行时处理重音符和变音符不正常
我正在尝试使用 scrapy 从一些源代码中打印页面标题到命令提示符/命令行。如果页面标题中有一些非标准字符(比如带重音符号的字母、变音符号等),就会出现错误。我试过以下几种方法:
myheader = titles.extract()[0]
myheader = str(myheader)
print '********** Page Title:', myheader.decode('utf-8'), '**********'
还有...
myheader = titles.extract()[0]
myheader = str(myheader)
print '********** Page Title:', myheader.decode(), '**********'
还有...
myheader = titles.extract()[0]
myheader = str(myheader)
print '********** Page Title:', myheader.encode('utf-8'), '**********'
我尝试打印的一个示例内容导致了这个错误:
<meta name="title" content="Mustang Cup Liga Postobón Clausura tables, rankings & standings | WhoScored.com">
这个内容在文本 'Mustang Cup Liga Postobón Clausura tables, rankings & standings | WhoScored.com"' 的第23个字符位置出错,因为这个位置的字母 'o' 上面有个重音符号。
实际的错误信息是:
exceptions.UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 23: ordinal not in range(128)
有没有人能告诉我为什么我上面的方法都不奏效呢?
谢谢
1 个回答
0
Selector.extract()
总是返回 unicode 的列表。- 使用
str
时要小心,它会用默认的编码方式(ascii)进行编码。
所以正确的做法是:
myheader = titles.extract()[0]
print u'********** Page Title: {} **********'.format(myheader).encode('utf-8')