从pptx中提取超链接

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。

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


谢谢。您的解决方案在我的环境中也运行成功了。 - Z.L

0

我无法帮助 Python 部分,但这里有一个示例,说明如何提取超链接 URL 本身,而不是应用于链接的文本,这是您想要的。

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接