【问题标题】:using python and lxml to crawl a page - (<type 'exceptions.UnicodeEncodeError'>, UnicodeEncodeError('ascii',使用 python 和 lxml 抓取页面 - (<type 'exceptions.UnicodeEncodeError'>, UnicodeEncodeError('ascii',
【发布时间】:2012-04-27 04:30:37
【问题描述】:

我正在使用 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。

谢谢

【问题讨论】:

    标签: python unicode lxml


    【解决方案1】:

    试试:

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

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

    【讨论】:

    • 然后您必须提供更多上下文,即回溯和它所引用的代码,以及您为数据库/表/列设置的编码。
    【解决方案2】:

    标头中所描述的用于编码的页面可能与实际情况不同。如果页面的实际编码不是 utf-8,那么做正确的事情就有点棘手了。

    首先你应该看看el.text_content()返回的文本

    x = el.text_content() print x

    如果你还有一些像/x09这样的编码字符串,这意味着它还没有被解码。

    如果 x 是 unicode,(以 'u' 开头)你应该将 unicode 转换为 str 并使用适当的编码(如 cp1252 或 sth)对其进行解码

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-06
      • 2016-04-20
      相关资源
      最近更新 更多