从pptx中提取超链接

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

我想从pptx中提取超链接,我知道如何在word中提取,但是有人知道如何从pptx中提取它吗?

例如,我在 pptx 中有一段文本,我想获取 url https://stackoverflow.com/ :


你好,stackoverflow


我尝试编写Python代码来获取文本:

from pptx import Presentation
from pptx.opc.constants import RELATIONSHIP_TYPE as RT

ppt = Presentation('data/ppt.pptx')

for i, sld in enumerate(ppt.slides, start=1):
    print(f'-- {i} --')
    for shp in sld.shapes:
        if shp.has_text_frame:
            print(shp.text)

但我只想打印带有超链接的文本和URL。

python powerpoint python-pptx
3个回答
2
投票

python-pptx
中,超链接可以出现在
Run
上,我相信这就是您所追求的。请注意,这意味着零个或多个超链接可以出现在给定的形状中。另请注意,超链接也可以出现在整个形状上,这样单击形状就会跟随链接。在这种情况下,URL 的文本不会出现。

from pptx import Presentation

prs = Presentation('data/ppt.pptx')

for slide in prs.slides:
    for shape in slide.shapes:
        if not shape.has_text_frame:
            continue
        for paragraph in shape.text_frame.paragraphs:
            for run in paragraph.runs:
                address = run.hyperlink.address
                if address is None:
                    continue
                print(address)

文档的相关部分在这里:
https://python-pptx.readthedocs.io/en/latest/api/text.html#run-objects

这里:
https://python-pptx.readthedocs.io/en/latest/api/action.html#hyperlink-objects


0
投票

我无法帮助解决 python 部分,但这里有一个示例,说明如何提取超链接 URL 本身,而不是提取链接所应用的文本,这正是您所追求的。

PPT 中的每张幻灯片都有一个 Hyperlinks 集合,其中包含幻灯片上的所有超链接。每个超链接都有一个 .Address 和 .SubAddress 属性。例如,对于像 https://www.someplace.com#placeholder 这样的 URL,.Address 将是 https://www.someplace.com,.SubAddress 将是占位符。

Sub ExtractHyperlinks()

Dim oSl As Slide
Dim oHl As Hyperlink
Dim sOutput As String

' Look at each slide in the presentation
For Each oSl In ActivePresentation.Slides
    sOutput = sOutput & "Slide " & oSl.SlideIndex & vbCrLf
    ' Look at each hyperlink on the slide
    For Each oHl In oSl.Hyperlinks
        sOutput = sOutput & vbTab & oHl.Address & " | " & oHl.SubAddress & vbCrLf
    Next    ' Hyperlink
Next    ' Slide

Debug.Print sOutput

End Sub

0
投票

这对我有用,使用 win32com 库:

import win32com.client
filename = 'data/ppt.pptx'
PptApp = win32com.client.Dispatch("Powerpoint.Application")
PptApp.Visible = True
pptx = PptApp.Presentations.Open(filename, ReadOnly= False)
for slide in pptx.slides:
    for shape in slide.shapes:
        try:
            if not shape.hasTextFrame:
                continue
        except:
            pass
        text = shape.textFrame.TextRange.Text
        if r"://" in text:
            print(text)
PptApp.Quit()
pptx =  None
PptApp = None
© www.soinside.com 2019 - 2024. All rights reserved.