如何使用python从docx文件中提取超链接中的url

时间:2016-11-07 22:23:16

标签: python python-docx

我一直试图找出如何使用python从docx文件中获取url,但未能找到任何内容,我已经尝试过python-docx和python-docx2txt,但是python-docx似乎只提取了文本,而python-docx2txt能够从超链接中提取文本,但不能从网址中提取文本。

5 个答案:

答案 0 :(得分:1)

我使用以下代码解决了它,以便从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)

答案 1 :(得分:0)

你可以使用wps另存为.hml文件,然后运行文件

答案 2 :(得分:0)

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

这将删除错误。

答案 3 :(得分:0)

我迟到了这个派对,但是如果你想要从.docx文件中提取所有链接的东西并制作它们的电子表格(或返回它们的列表),我有一个脚本可能会这样做您。它包括URL和链接文本,如果需要,您可以将其提供给整个文件夹。

https://github.com/Colin-Fredericks/hx-py/blob/master/XML_utilities/GetWordLinks.py

它使用BeautifulSoup和UnicodeCSV,你也可以从同一个仓库中获取它们。在Python3中运行。文件顶部的说明。处理非ascii字符。到目前为止只在Mac和Ubuntu上测试过。尽管Google Drive可以,但Excel无法可靠地导入Unicode CSV。在禁止的地方提供void()。

答案 4 :(得分:0)

我是Python的初学者,并且有一个作业要使用Python来更改.docx文档中的每个超链接。感谢Kiran的代码,它给了我一些尝试,尝试和错误的提示,并最终使它起作用。这是我想要与其他初学者分享的代码。

# python to change docx URL hyperlinks:
### see: https://stackoverflow.com/questions/40475757/how-to-extract-the-url-in-hyperlinks-from-a-docx-file-using-python

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

print(" This program changes the hyperlinks detected in a word .docx file \n")

docx_file=input(" Pls input docx filename (without .docx): ")

document = Document(docx_file + ".docx")

rels = document.part.rels

for rel in rels:
   if rels[rel].reltype == RT.HYPERLINK:
      print("\n Origianl link id -", rel, "with detected URL: ", rels[rel]._target)
      new_url=input(" Pls input new URL: ")
      rels[rel]._target=new_url

out_file=docx_file + "-out.docx"

document.save(out_file)

print("\n File saved to: ", out_file)

谢谢你, 何丽萍