我正在抓取this link使用Python Scrapy。所有文件开头都有 # -*-coding: utf-8 -*-
为了提取产品标题,我有这个代码。
response.css("h1.d-title::text").extract_first()
这表明
2017\xe6\x98\xa5\xe5\xa4\x8f\xe6\x96\xb0\xe6\xac\xbe\xe5\xa5\xb3\xe5\xa3\xab\xe8\xbf\x90\xe5\x8a\xa8\xe9\x9e\x8b\xe9\x9f\xa9\xe7\x89\x88\xe4\xbc\x91\xe9\x97\xb2\xe7\xbd\x91\xe5\x8d\x95\xe9\x9e\x8bsport shoes men\xe5\xa4\x96\xe8\xb4\xb8\xe6\x89\xb9\xe5\x8f\x91
如果我这样做
response.css("h1.d-title::text").extract_first().decode('gbk').encode('utf-8')
它给了我错误
UnicodeEncodeError:“ascii”编解码器无法对位置 4-19 中的字符进行编码:序号不在范围内(128)
我在网上尝试过其他替代方法,但都不起作用。
尽管如果我在 Python 终端(没有 Scrapy)中执行此操作,它会完美地打印中文!
>>> s = "2017\xe6\x98\xa5\xe5\xa4\x8f\xe6\x96\xb0\xe6\xac\xbe\xe5\xa5\xb3\xe5\xa3\xab\xe8\xbf\x90\xe5\x8a\xa8\xe9\x9e\x8b\xe9\x9f\xa9\xe7\x89\x88\xe4\xbc\x91\xe9\x97\xb2\xe7\xbd\x91\xe5\x8d\x95\xe9\x9e\x8bsport shoes men\xe5\xa4\x96\xe8\xb4\xb8\xe6\x89\xb9\xe5\x8f\x91"
>>> print s
2017春夏新款女士运动鞋韩版休闲网单鞋sport shoes men外贸批发
为什么它能通过print
给出正确的输出?
最佳答案
Scrapy Selector会返回unicode字符串列表,引用Using selectors with regular expressions 。你需要做的就是将unicode编码为UTF-8,不需要解码为gbk然后编码回utf-8。
title = response.css("h1.d-title::text").extract_first().encode('utf-8')
对于在python终端中打印,我认为您的环境默认编码是UTF-8,您可以输入您的python终端:
>>> import sys
>>> print sys.stdout.encoding
UTF-8
当你打印unicode字符串时,它会转换为utf-8然后打印出来。
关于Python Scrapy不返回中文字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43752342/