使用 Python 和 win32com 检查 Microsoft Word 中的超链接

Checking Hyperlinks in Microsoft Word using Python and win32com

我正在开发一个程序,它将打开一个 Word 文档并检查该文档中的所有 link。如果任何 link 损坏,它应该报告。

我可以做到所有这些,使用 Python 的 win32com 库。

但是,目前我正在使用 HyperLink.follow() 检查每个 link。问题是它 实际上打开 每个文档,我的屏幕很快就会充满打开的文档(我的测试文件有大约 15 links 到不同的文档,我预计在生产中最多可达数百个)。

我怎样才能阻止这种情况发生?我有一些想法,但不知道如何去做:

当前节目:

#settings
debug = True

# Open a specified word document
wordapp = win32com.client.Dispatch('Word.Application')
wordapp.Visible = debug

directory = os.path.dirname(__file__)
filename = '0 - Cover.docx'
document_location = os.path.join(directory, filename)

if debug == True:
    print(document_location)

document = wordapp.Documents.Open(document_location)

if debug == True:
    print("Document opened succesfully.")

# Gimme the links
wordapp.ActiveDocument

for link in (wordapp.ActiveDocument.HyperLinks):
    print(link.Name)

    try:
        link.Follow()
    except:
        print("This link is broken.")
    else:
        print("This link did not raise an error.")

A Hyperlink 有两个属性 -- Address,其中(对于本地文件)包含文件系统;和 SubAddress(对于本地文件)指的是所引用项目中的位置——Word 书签的名称,或 Excel 命名的单元格范围等。

检查 Address 是否映射到文件系统上的文件可能就足够了,根本不需要打开文档。 OTOH 这不会告诉你 link 是否完全起作用,因为 SubAddress 可能指的是一个不存在的名称。

如果您想检查 hyperlink 的全部功能,并且所有这些都应该引用 Word 文档,它们可能会在当前 申请。如果是这样,那么您可以使用名称以编程方式访问新打开的文档,然后将其关闭:

import os

opened_doc = wordapp.Documents(os.path.basename(link.Address))
opened_doc.Close()

注意事项:

  • 以上仅适用于加载到当前 Application 中的文档。这不包括其他文件类型(Excel 电子表格、Powerpoint 演示文稿)或在另一个 Application 实例中打开的 Word 文档。
  • client.Dispatch支持隐形载入文件不太准确;它是默认情况下不可见加载的 Word 对象模型。无论如何,这与 Hyperlink.Follow 无关,后者(如果我理解正确的话)取决于系统 API 以使用适当的应用程序打开相关文档。