首页 > 解决方案 > python - 如何提取 DOCX 超链接的文本?

问题描述

基于此解决方案

from docx import Document
from docx.opc.constants import RELATIONSHIP_TYPE as RT

document = Document('test.docx')
rels = document.part.rels

def iter_hyperlink_rels(rels):
    for rel in rels:
        if rels[rel].reltype == RT.HYPERLINK:
            yield rels[rel]._target      

print(iter_hyperlink_rels(rels)

我需要获取超链接的 url文本(例如mydomain.com,用于 url 和Go to My Domain文本)

标签: pythondocx

解决方案


回答我自己的问题,我必须通过html这样做:

from bs4 import BeautifulSoup
with open('my_word_file.htm', 'r') as file:
    page = file.read()
soup = BeautifulSoup(page, 'lxml')

text_and_url = []
for link in soup.findAll('a'):
    text_and_url.append({'text':link.string, 'url':link.get('href')})

docx文件转换html

如何使用 python 将 .docx 文件转换为 html?


推荐阅读