如何将带有图像的Docx文件发布到WordPress站点?

2024-06-26 04:30:50 发布

您现在位置:Python中文网/ 问答频道 /正文

因此,我能够使用WP REST-API将Docx文件发布到WordPress,使用Python中的mammoth Docx包 我可以上传一张图片到WordPress

但是当docx文件中有图像时,它们不会上传到WordPress媒体部分

有什么意见吗

我正在为此使用python。 以下是Docx到HTML转换的代码

        with open(file_path, "rb") as docx_file:
            # html = mammoth.extract_raw_text(docx_file)
            result = mammoth.convert_to_html(docx_file, convert_image=mammoth.images.img_element(convert_image))
            html = result.value  # The generated HTML

请注意,我能够在实际发布的帖子中看到图片,但它们有一个奇怪的源图片URL&;没有出现在WordPress媒体部分。 怪异的图像源URL 数据:图像/jpeg;base64,/9j/4AAQSKZJRGABAQAAAQABAD/2WBDAAEBAQEBAQEBAQEBAQEBAQEBQUEBAQFBCGBQUBGQEBGKGBGICAGIBQYJCGKICGICAJ/2WBDAQEBAQBAQIQACAGQQCAGICAGICAGICAGICAGICAGICAGICAGICAGICAGICAGICAGICAGICAJ/WAARCAUQABQQBQUBQUBGUKGKGKGKGKGBGIBQGIBQIBQYJCGKIGCCAJAJ/2WBAQBAQEBAQBAQQQQQQBAQBAQBAQBAQBAQCAGICAGICAGICAGICAGICAGICAGICAGICAGICAGICAGICAGICAGICAGICAGICAGICAGICAGICAGICAGICAGICAGICAGICA;诸如此类

同时,非常感谢贡献者为WordPress提供了Pythonrepo


Tags: 文件图像imageurlconverthtmlwordpress图片
1条回答
网友
1楼 · 发布于 2024-06-26 04:30:50

mammothcli有一个函数,可以提取图像,将它们保存到目录中,并在html代码的img标记中插入文件名。如果不想在命令行中使用mammoth,可以使用以下代码:

import os
from mammoth.cli import ImageWriter, _write_output

output_dir = './output'
filename = 'filename.docx'

with open(filename, "rb") as docx_fileobj:
    convert_image = mammoth.images.img_element(ImageWriter(output_dir))
    output_filename = "{0}.html".format(os.path.basename(filename).rpartition(".")[0])
    output_path = os.path.join(output_dir, output_filename)
    
    result = mammoth.convert(
        docx_fileobj,
        convert_image=convert_image,
        output_format='html',
    )
    _write_output(output_path, result.value)

请注意,在将图像上载到Wordpress时,仍然需要更改img链接,但这解决了映射问题。您可能还希望更改^{}类以将图像保存到tiff以外的其他位置

相关问题 更多 >