【问题标题】:Python convert docx to html using mammoth: html, head and body tag missingPython 使用 mammoth 将 docx 转换为 html:缺少 html、head 和 body 标签
【发布时间】:2020-03-25 12:18:57
【问题描述】:

我正在尝试使用 mammoth 包将简单的 docx 文件转换为 HTML 文件。但是生成的 html 似乎只包含完整 HTML 文件的一部分:生成的 html 字符串中都缺少 HTML、head 和 body 标记。

不知道有没有参数可以让HTML变成有效的HTML代码。

【问题讨论】:

    标签: python html mammoth


    【解决方案1】:

    我阅读了文档,但没有找到生成完整 HTML 的选项。由于生成的 HTML 只是一个字符串,因此很容易使其完全兼容 HTML:

    import mammoth
    
    with open("test.docx", "rb") as docx_file:
        result = mammoth.convert_to_html(docx_file)
        html = result.value  # The generated HTML
        messages = result.messages  # Any messages,
    
        full_html = (
            '<!DOCTYPE html><html><head><meta charset="utf-8"/></head><body>'
            + html
            + "</body></html>"
        )
    
        with open("test.html", "w", encoding="utf-8") as f:
            f.write(full_html)
    

    在上面的代码中,我们只是在前面加上必要的开始和结束标记,以使html 字符串成为有效的 HTML 源代码。

    【讨论】:

      猜你喜欢
      • 2022-06-10
      • 2020-04-18
      • 1970-01-01
      • 1970-01-01
      • 2011-09-12
      • 2013-03-29
      • 1970-01-01
      • 1970-01-01
      • 2013-01-27
      相关资源
      最近更新 更多