【问题标题】:unicode() argument 2 must be string not Noneunicode() 参数 2 必须是字符串而不是 None
【发布时间】:2015-06-18 11:57:00
【问题描述】:

我正在尝试解析包含 html 内容的电子邮件的内容。

import imaplib
import email
....
    elif part.get_content_type() == "text/html":
        # if html is None:
        html = ""
        html += unicode(part.get_payload(decode=True),part.get_content_charset(),'replace').encode('utf8','replace')
        save_string = str("C:Dumpgmailemail2"+".eml")
        # location on disk
        myfile = open(save_string, 'a')
        myfile.write(str(html))
        #myfile.write(html.decode('utf-8'))
        myfile.close()

但这给了我一个错误:

Traceback (most recent call last):
  File "extract.py", line 22, in <module>
    html += unicode(part.get_payload(decode=True),part.get_content_charset(),"replace").encode('utf8','replace')
TypeError: unicode() argument 2 must be string, not None

【问题讨论】:

  • part.get_content_charset() 正在返回无,使用默认值

标签: python html email parsing unicode


【解决方案1】:

似乎 part.get_content_charset()None ,如果它 None 给 unicode() 函数,也许你可以提供一些默认值 -

html += unicode(part.get_payload(decode=True),part.get_content_charset() if part.get_content_charset() is not None else 'utf-8' ,'replace').encode('utf8','replace')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-28
    • 2023-03-09
    • 1970-01-01
    • 2017-01-12
    • 1970-01-01
    • 2019-07-07
    • 2022-01-09
    相关资源
    最近更新 更多