【问题标题】:Python + Scrapy + MySQL UTF8 Encoding errorPython + Scrapy + MySQL UTF8 编码错误
【发布时间】:2016-03-12 21:44:55
【问题描述】:

我有一个抓取网站并写入 MySQL 的抓取代码

import MySQLdb.cursors

def __init__(self,stats):
    self.dbpool = adbapi.ConnectionPool(<dbnam>,host=<host>,user=<user>,port=<port>,passwd=<pwd>, db=<dbname>, cursorclass=MySQLdb.cursors.DictCursor, charset='utf8', use_unicode=True)

def process_item(self, item, spider):
    query = self.dbpool.runInteraction(self._conditional_insert, item)
    query.addErrback(self.handle_error)

用于表格中数字列表的 Scrapy 脚本

item['numbers'] = sites.xpath('//*[@id="numbers-0"]/tbody/tr/td/text()').extract()

我正在抓取以下内容:10″ 11″ 12″ 等。我的代码返回以下内容:

'numbers': [u'10\u2033', u'11\u2033', u'12\u2033'],

将其插入 MySQL 数据库会引发错误消息 - 我猜是由于 unicode 问题。

tx.execute("""INSERT INTO numbers ('{0}').format(", ".join(item['numbers'])))

能否请您帮助插入成功。更好的是,如何从列表中删除特殊字符“\u2033”?

提前致谢!

【问题讨论】:

  • 你使用的是 Python 2 还是 Python 3?
  • 2.7.11 感谢 Bernard 对此进行调查!
  • 不用担心,您介意尝试使用PyMySQL 而不是 MySQL 连接器吗?
  • 从 MYSQL 连接器移动完全没有问题。我是 Python 和 Scrapy 的新手。只需要弄清楚如何使用 PyMySQL
  • 执行与连接器完全相同的操作,只需将pymysql 放在适当的位置即可。并安装它运行sudo pip install PyMySQL

标签: python mysql unicode utf-8 scrapy


【解决方案1】:

您可能会收到 UnicodeEncodeError,因为您正试图将包含非 ascii 字符的 unicode 字符串插入到字节字符串中。

要解决此问题,请确保您的查询字符串具有 u 前缀:

tx.execute(u"""INSERT INTO numbers ('{0}')""".format(", ".join(item['numbers'])))

如果你真的想摆脱那些双撇号字符,我想你可以用双引号替换它们:

item['numbers'] = [s.replace(u'\u2033', '"') for s in item['numbers']]

但我认为最好确保您的代码能够处理抛出的任何 unicode 字符 - 也就是说,您应该始终在程序中使用 unicode 字符串。

【讨论】:

  • 我不能赞成你的答案,因为我是 stackoverflow 的新手。一旦我赢得了一些信誉,就会回来! :)
  • @user6055239。谢谢 :) 注意:你总是可以accept answers,这也会为你赢得一点声望。
猜你喜欢
  • 1970-01-01
  • 2013-06-11
  • 2012-11-13
  • 1970-01-01
  • 1970-01-01
  • 2016-12-03
  • 1970-01-01
  • 2012-07-26
相关资源
最近更新 更多