使用python提取docx文件中的所有图像

Him*_*dar 4 python glob image docx win32com

我有一个 docx 文件,其中包含 6-7 张图像。我需要自动从此文档文件中提取图像。有没有win32com相同的 ms word API?或者有什么库可以准确提取其中的所有图像?

这是我尝试过的,但问题首先是它没有给我所有的图像,其次它给了我许多错误的积极图像,比如空白图像、极小的图像、线条等......它也使用了 MS 词做同样的事情。

from pathlib import Path
from win32com.client import Dispatch

xls = Dispatch("Excel.Application")
doc = Dispatch("Word.Application")


def export_images(fp, prefix="img_", suffix="png"):
    """ export all of images(inlineShapes) in the word file.
    :param fp: path of word file.
    :param prefix: prefix of exported images.
    :param suffix: suffix of exported images.
    """

    fp = Path(fp)
    word = doc.Documents.Open(str(fp.resolve()))
    sh = xls.Workbooks.Add()
    for idx, s in enumerate(word.inlineShapes, 1):
        s.Range.CopyAsPicture()
        d = sh.ActiveSheet.ChartObjects().add(0, 0, s.width, s.height)
        d.Chart.Paste()
        d.Chart.Export(fp.parent / ("%s_%s.%s" % (prefix, idx, suffix))
    sh.Close(False)
    word.Close(False)
export_images(r"C:\Users\HPO2KOR\Desktop\Work\venv\us2017010202.docx")
Run Code Online (Sandbox Code Playgroud)

您可以在此处下载 docx 文件https://drive.google.com/open?id=1xdw2MieI1n3ulXlkr_iJSKb3cbozdvWq

Ald*_*ven 5

您可以解压缩所有按docx大小初步过滤的图像:

import zipfile

archive = zipfile.ZipFile('file.docx')
for file in archive.filelist:
    if file.filename.startswith('word/media/') and file.file_size > 300000:
        archive.extract(file)
Run Code Online (Sandbox Code Playgroud)

您的示例 5图像中找到:

在此输入图像描述