使用python和lxml来抓取页面 - (<type'exception.unicodeencodeerror'=“”>,UnicodeEncodeError('ascii',</type>

时间:2012-04-15 16:51:49

标签: python unicode lxml

我正在使用python2.7和lxml来获取页面。我一直收到以下错误。

(<type 'exceptions.UnicodeEncodeError'>, UnicodeEncodeError('ascii', u'Approximate Dimensions: 4\xbd" x 4" x 7" (assembled)', 25, 26, 'ordinal not in range(128)'), <traceback object at 0x7f9198ac48c0>)

我尝试了以下内容:

doc = lxml.html.document_fromstring(html)
for el in doc.iter('h2'):
    el.text_content().decode('utf-8','ignore')
    OR
    el.text_content().encode('ascii', 'ignore')

如何解决这些错误?我需要能够1)保存到文本文件然后2)将文本文件上传到MySQL。

由于

2 个答案:

答案 0 :(得分:2)

尝试:

el.text_content().encode('utf-8')

它是unicode,你想将它(作为文本)存储到utf-8。

答案 1 :(得分:0)

页面用于编码的标题可能与实际不同。如果网页的实际编码不是utf-8,那么做正确的业务就会有点麻烦。

首先,您应该查看el.text_content()

中返回的文字

x = el.text_content() print x

如果您仍然使用/x09这样的编码字符串,则意味着它尚未解码。

如果x是unicode,(从&#39; u&#39;开始),您应该将unicode转换为str并使用正确的编码对其进行解码(例如cp1252或者......)

chars = ''.join([chr(ord(x)) for x in el.text_content()]) /// It will change your dumb unicode to str result = chars.decode({try with different encoding until it doesn't throw an error}) /// now you decode str with proper format

相关问题