from docx import Document,oxml
from docx.oxml.shared import qn
from docx.text.paragraph import Paragraph
from docx.oxml import OxmlElement
defget_bookmark_par_element_start(document, bookmark_name):"""查找标签的起始位置(所在的段落)"""
doc_element = document.part.element
bookmarks_list = doc_element.findall('.//'+ qn('w:bookmarkStart'))for bookmark in bookmarks_list:
name = bookmark.get(qn('w:name'))if name == bookmark_name:
par = bookmark.getparent()ifnotisinstance(par, oxml.CT_P):print('par不是CT_P类型,返回2')return2else:print(type(par))#return par, bookmark.get(qn('w:id'))return par
print('没找到书签,返回1')return1
#查找书签的结束位置(所在的段落)defget_bookmark_par_element_end(document, bookmark_id):
doc_element = document.part.element
bookmarks_list = doc_element.findall('.//'+ qn('w:bookmarkEnd'))for bookmark in bookmarks_list:
name = bookmark.get(qn('w:id'))if name == bookmark_id:
par = bookmark.getparent()ifnotisinstance(par,oxml.CT_P):return2else:return par
return1