【问题标题】:EncodeError with \xa3 (pound sign)带有 \xa3 的编码错误(井号)
【发布时间】:2015-07-31 12:33:50
【问题描述】:

我正在尝试从网页中获取一些数据。该网页已声明字符集为 utf-8。但是 \xa3 符号有问题。我无法被编码或解码为“utf-8”。

for key,value in self.__dict__.iteritems():
            if key not in self.db_attributes:
                print repr(value)
                attrs_statement+=str(key)+', '
                values_statement+=str(value)+', '

错误:

u'\xa3410'
Traceback (most recent call last):
  File "C:\Users\Milano\My Documents\LiClipse Workspace\Velvet_scraper\vehicle.py", line 432, in <module>
    v.prepare_insert_statement('motorhog_temp')
  File "C:\Users\Milano\My Documents\LiClipse Workspace\Velvet_scraper\vehicle.py", line 381, in prepare_insert_statement
    values_statement+=str(value)+', '
UnicodeEncodeError: 'ascii' codec can't encode character u'\xa3' in position 0: ordinal not in range(128)

请问这是怎么回事?

编辑:

整个方法:

def prepare_insert_statement(self,table):
        log('prepare_insert_statement, table: {0}'.format(table))

        attrs_statement = "("
        values_statement = "("

        for key,value in self.__dict__.iteritems():
            if key not in self.db_attributes:
                print repr(value)
                attrs_statement+=key+', '
                values_statement+=value+', '

        attrs_statement+=')'
        values_statement+=')'
        statement = """INSERT INTO TABLE {0}{1} VALUES{2}""".format(table,attrs_statement,values_statement)
        return statement

【问题讨论】:

  • values_statement是什么类型的对象?

标签: python encoding decoding


【解决方案1】:

str() 使用 ASCII 编解码器隐式编码 Unicode 对象。显式编码您的对象,或者不使用 str() 对象并构建一个 Unicode 字符串:

values_statement += value.encode('utf8') + ', '

【讨论】:

  • 谢谢,我删除了 str() ,它似乎有帮助。但是现在,它在最后一行 """INSERT INTO table...""" 上引发了同样的事情(UnicodeEncodeError for \xa3)我已经编辑了我的代码,所以你可以在那里看到它。
  • @Milan:您应该不对数据库插入使用字符串插值。使用 SQL 参数并将编码 Unicode 数据留给数据库驱动程序。
猜你喜欢
  • 1970-01-01
  • 2011-02-04
  • 1970-01-01
  • 1970-01-01
  • 2011-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-02
相关资源
最近更新 更多