使用python将dox文件的图片取出来
时间: 2024-05-03 20:22:21 浏览: 8
有几种方法可以从docx文件中提取图片,以下是其中两种方法:
方法一:使用python-docx库
```python
import docx
# 打开docx文件
doc = docx.Document('example.docx')
# 遍历所有段落并提取图片
for para in doc.paragraphs:
for run in para.runs:
if run._element.tag.endswith('}rPr'):
for child in run._element:
if child.tag.endswith('}drawing'):
for grandchild in child:
if grandchild.tag.endswith('}graphic'):
for greatgrandchild in grandchild:
if greatgrandchild.tag.endswith('}graphicData'):
for item in greatgrandchild:
if item.tag.endswith('}pic'):
for i in item:
if i.tag.endswith('}blipFill'):
for j in i:
if j.tag.endswith('}blip'):
# 提取图片
img_data = j.attrib['{http://schemas.openxmlformats.org/officeDocument/2006/relationships}embed']
img_name = 'image_' + img_data.split('rId')[-1] + '.jpeg'
with open(img_name, 'wb') as f:
f.write(doc.part.related_parts[img_data].blob)
```
方法二:使用python unzip库
```python
import os
import zipfile
# 打开docx文件
docx_file = 'example.docx'
zip_docx = zipfile.ZipFile(docx_file)
# 遍历所有文件并提取图片
for file in zip_docx.namelist():
if file.endswith(('.jpeg', '.jpg', '.png', '.bmp')):
img_name = os.path.basename(file)
img_data = zip_docx.read(file)
with open(img_name, 'wb') as f:
f.write(img_data)
```