【发布时间】:2015-03-19 13:49:30
【问题描述】:
我在使用 Scrapy 时遇到编码问题,希望有人能帮助我。
- 在我的蜘蛛上:
item['title'] = html.xpath('.//h5/text()') - 在管道上:
item['title'] = item['title'].extract()[0].encode('utf-8', 'replace')
它的结果字符串类似于Namontana \xe2\x80\x93 Une attaque \xc3\xa0 main arm\xc3\xa9e avort\xc3\xa9e。我将所有项目保存在数据库中(现在是 mysql)。
现在我想向网站显示所有这些项目,但我的问题是我无法将 \xe2(例如)转换为可视字符。
我已经试过了:
- 在所有 .py 文件的开头添加
# -*- coding: utf-8 -*- - 使用 PHP 代码显示时使用
htmlentities或utf8_decode函数 - 在我的蜘蛛上添加
unicode(response.body.decode(response.encoding)).encode('utf-8') - 将
<meta http-equiv="content-type" content="text/html; charset=utf-8" />添加到我的 HTML 页面 - 检查所有文件并将其转换为不带 BOM 的 UTF8
目前,我唯一的选择是使用自定义函数来替换所有字符(解释here),但我认为他们有更好的解决方案。
提前感谢您的帮助。
【问题讨论】:
标签: python mysql encoding utf-8 scrapy