EncodeError with \ xa3(井号)

时间:2015-07-31 12:33:51

标签: python encoding decoding

我试图从网页上获取一些数据。这个网页上说charset是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)+', '

ERROR:

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

1 个答案:

答案 0 :(得分:4)

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

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