我使用Python Scrapy抓取this link。所有的文件都有# -*- coding: utf-8 -*-
在开始Python Scrapy不返回中文字符
并提取产品的标题,我有这个代码。
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' codec can't encode characters in position 4-19: ordinal not in range(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
?