我正在解析用西班牙语写的网页scrapy。问题是,由于编码错误,我无法保存文本。解析西班牙语文本并将其保存在分号中
这是解析函数:
def parse(self, response):
hxs = HtmlXPathSelector(response)
text = hxs.select('//text()').extract() # Ex: [u' Sustancia mineral, m\xe1s o menos dura y compacta, que no es terrosa ni de aspecto met\xe1lico.']
s = "".join(text)
db = dbf.Dbf("test.dbf", new=True)
db.addField(
("WORD", "C", 25),
("DATA", "M", 15000), # Memo field
)
rec = db.newRecord()
rec["WORD"] = "Stone"
rec["DATA"] = s
rec.store()
db.close()
当我尝试将其保存到一个分贝(A DBF数据库)我得到一个ASCII(128)错误。我尝试使用'utf-8'和'latin1'进行解码/编码,但没有成功。
编辑:
为了节省我使用dbfpy分贝。我在上面的解析函数中添加了dbf保存代码。
这是错误消息:
Traceback (most recent call last):
File "/usr/lib/python2.6/dist-packages/twisted/internet/base.py", line 1179, in mainLoop
self.runUntilCurrent()
File "/usr/lib/python2.6/dist-packages/twisted/internet/base.py", line 778, in runUntilCurrent
call.func(*call.args, **call.kw)
File "/usr/lib/python2.6/dist-packages/twisted/internet/defer.py", line 280, in callback
self._startRunCallbacks(result)
File "/usr/lib/python2.6/dist-packages/twisted/internet/defer.py", line 354, in _startRunCallbacks
self._runCallbacks()
--- <exception caught here> ---
File "/usr/lib/python2.6/dist-packages/twisted/internet/defer.py", line 371, in _runCallbacks
self.result = callback(self.result, *args, **kw)
File "/home/katy/Dropbox/proyectos/rae/rae/spiders/rae_spider.py", line 54, in parse
rec.store()
File "/home/katy/Dropbox/proyectos/rae/rae/spiders/record.py", line 211, in store
self.dbf.append(self)
File "/home/katy/Dropbox/proyectos/rae/rae/spiders/dbf.py", line 214, in append
record._write()
File "/home/katy/Dropbox/proyectos/rae/rae/spiders/record.py", line 173, in _write
self.dbf.stream.write(self.toString())
File "/home/katy/Dropbox/proyectos/rae/rae/spiders/record.py", line 223, in toString
for (_def, _dat) in izip(self.dbf.header.fields, self.fieldData)
File "/home/katy/Dropbox/proyectos/rae/rae/spiders/fields.py", line 215, in encodeValue
return str(value)[:self.length].ljust(self.length)
exceptions.UnicodeEncodeError: 'ascii' codec can't encode character u'\xf1' in position 18: ordinal not in range(128)
你可以发布你看到的实际错误,以及导致它的代码吗? – SimonJ 2010-11-13 23:34:45
所以你从你的网页上获得unicode。这很好,就像它应该那样。这不是你的问题。你的问题是“将它保存为dbf数据库” - 你需要显示试图这样做的代码;我们没有水晶球。您需要给我们一个指向您正在使用的dbf-handling模块的链接。 – 2010-11-13 23:36:13
另请确认您的意思是dBase III等Visual Foxpro使用的DBF文件 - 如果不是,它是什么? – 2010-11-13 23:43:09