.docx 文档没有属性 'xpath' 的属性错误

Attribute error with .docx document no attribute 'xpath'

from docx import *
document = Document(r'filepath.docx')
words = document.xpath('//w:r', namespaces=document.nsmap)
WPML_URI = '{http://schemas.openxmlformats.org/wordprocessingml/2006/main'
tag_rPr = WPML_URI + 'rPr'
tag_highlight = WPML_URI + 'highlight'
tag_val = WPML_URI + 'val'
tag_t = WPML_URI + 't'
for word in words:
    for rPr in word.findall(tag_rPr):
        high = rPr.findall(tag_highlight)
        for hi in high:
            if hi.attribute[tag_val] == 'yellow':
                print(word.find(tag_t).text.encode('utf-8').lower())

理论上这段代码应该获取文档文本,然后找到黄色突出显示的文本,但我的问题是在开始时我 运行 代码是这样的,我得到 AttributeError: 'Document' object has no attribute 'xpath' 作为错误信息。它的问题显然是 words = document.xpath('//w:r', namespaces=document.nsmap) 我不知道如何解决

问题是您正试图对 docx.Document 做一些不允许的事情。如果您查看 here,您可以看到关于此的文档,并且 .xpath 对于 Document 不存在。

如果您需要这些词,您可以通过 Document.paragraph 方法获取它们 - 也在链接的文档中。

@PirateNinjas 就在眼前。 Document object 不是 lxml.etree._Element 的子类,因此没有 .xpath() 方法。 AttributeError就是这个意思; object 上的每个方法都是一个属性(就像实例变量一样),如果不存在具有您要求的名称的方法,则会出现此错误。

但是,Document._element _Element 的子类,可能对您有用。至少它不会给你这个错误,并且应该让你朝着正确的方向前进。此代码应为您提供文档主要故事中的所有 <w:r> 元素(即文档 body,但不包括 headers、脚注等):

rs = document._element.xpath("//w:r")
from docx import *
document = Document('xyz.docx')
words = document._element.xpath('//w:r')
WPML_URI = "{http://schemas.openxmlformats.org/wordprocessingml/2006/main}"
tag_rPr = WPML_URI + 'rPr'
tag_highlight = WPML_URI + 'highlight'
tag_val = WPML_URI + 'val'
tag_t = WPML_URI + 't'
for word in words:
    for rPr in word.findall(tag_rPr):
        high=rPr.findall(tag_highlight)
        for hi in high:
            if hi.attrib[tag_val] in ['yellow','blue','green']:
                 print(word.find(tag_t).text.encode('utf-8'))

如果要提取黄色文本,请使用这行代码:

if hi.attrib[tag_val] == 'yellow':