Python通过python-docx库或手动解压.docx ZIP包来解析其内部XML文件;前者用_element.xml获取段落等原始XML,后者用zipfile+etree/lxml读取document.xml等核心文件,并需正确处理命名空间。
Python本身不直接解析Word文档的底层XML,而是通过python-docx库操作.docx文件——因为.docx本质是ZIP压缩包,内部包含多个XML文件(如document.xml、styles.xml等)。若需访问原始XML数据,有两种主流方式:一是用python-docx间接获取XML片段;二是手动解压.docx并解析目标XML文件。
python-docx虽为高层接口,但每个元素(如Paragraph、Run)都提供_element属性,可直接访问底层lxml Element对象,进而读取或修改其XML。
pip install python-docx lxml
from docx import Documentdoc = Document("example.docx") p = doc.paragraphs[0] # 获取第一个段落 xml_str = p._element.xml # 返回该段落的完整XML字符串(含命名空间) print(xml_str[:200]) # 查看前200字符
_element.xml返回的是带namespaces的原始XML,可能含w:前缀(如),解析时需处理命名空间或用lxml的XPath配合{http://schemas.openxmlformats.org/wordprocessingml/2006/main}。.docx是ZIP格式,可用Python内置zipfile模块解压,再用xml.etree.ElementTree或lxml解析指定XML。
word/document.xml:主文档内容(段落、文字、制表符等)word/styles.xml:样式定义word/numbering.xml:编号与项目符号规则word/settings.xml:文档设置document.xml中的所有段落文本(忽略格式):
import zipfile import xml.etree.ElementTree as ETwith zipfile.ZipFile("example.docx") as docx: with docx.open("word/document.xml") as f: tree = ET.parse(f) root = tree.getroot()
Word XML默认命名空间
ns = {"w": "http://schemas.openxmlformats.org/wordprocessingml/2006/main"} for p in root.findall(".//w:p", ns): text = "".join(t.text for t in p.findall(".//w:t", ns) if t.text) print(text.strip())
当需XPath查询、命名空间灵活处理、或修改后重新打包时,lxml比标准库更强大。
pip install lxml
from lxml import etree import zipfilewith zipfile.ZipFile("example.docx") as docx: with docx.open("word/document.xml") as f: tree = etree.parse(f)
使用XPath查找所有应用了"Heading1"样式的段落
ns = {"w": "http://schemas.openxmlformats.org/wordprocessingml/2006/main"} headings = tree.xpath("//w:p[w:pPr/w:pStyle[@w:val='Heading1']]", namespaces=ns) for h in headings: text = "".join(h.xpath(".//w:t/text()", namespaces=ns)) print("标题:", text.strip())
tree.write()保存,并用zipfile重建.docx(需保留其他文件结构)。直接操作XML有风险,务必备份原文件;且Word生成的XML结构较复杂,嵌套深、命名空间多。
w:等前缀,XPath或find操作必须声明对应URI,否则查不到节点。zipfile.open()返回bytes,etree.parse()和lxml.etree.parse()能自动识别,无需手动decode。word/med
ia/,页眉页脚在word/header.xml/footer.xml,需单独解压读取。python-docx生成,仅在特殊分析场景才深入XML层。