AttributeError:“ NoneType”对象没有属性“名称”,当我尝试获取docx文件的标题时发生错误

问题描述 投票:0回答:1

我是python编程的新手。我正在使用docx模块来处理文档。当我尝试使用paragraph.style.name从docx文件中读取标题时,我得到:

AttributeError: 'NoneType' object has no attribute 'name'

我的脚本:]

from docx import Document  
document=Document('C:\\Users\\abc\\Desktop\\check\\Leave_Policy_converted.docx')
for paragraph in document.paragraphs:
    if paragraph.style.name == 'Heading 1':
        print (paragraph.text)

请澄清我。预先谢谢你。

python python-3.x python-docx
1个回答
1
投票

这意味着您要访问的属性是None(不是真实值)。

您需要检查paragraph.style是否为None,并且无法访问.style.name

if paragraph.style is not None and paragraph.style.name == 'Heading 1':
  print(paragraph.text)
© www.soinside.com 2019 - 2024. All rights reserved.