Word hyperlinks: changing only the visible text isn't enough — you must also check the target

Explains how to replace the visible text of Word hyperlinks with python-docx by editing the Hyperlink object, not paragraph-level text, so the URL target is preserved. Includes a runnable example, boundary acceptance table, and OmniDoc integration tips for translation and content cleaning.

Key Points of This Article

  • Directly assigning a value to the paragraph's text will overwrite the entire paragraph, and the hyperlinks along with their URL relationships will be lost.
  • Traverse the Hyperlink objects via iter_inner_content, and replace the text of their child Runs.
  • For hyperlinks spanning multiple Runs, first clear all child Runs before writing the translation; otherwise, residual source text will remain.
  • For internal bookmark links, the address is empty; the fragment should be preserved and its target left unmodified.
  • Hyperlinks that span page breaks, content controls, or fields should be flagged for manual review.

This article is written for developers who do translation or content cleaning on Word documents. Many people use scripts to replace hyperlink text, and afterward clicking the link does nothing or jumps to the wrong page. Below, we explain where the problem lies, how to safely modify the visible text with python-docx, and which edge cases to check before delivery.

This document uses synthetic samples to demonstrate the processing method. Before processing important files, keep the original, and review them against the boundaries and acceptance items described in the text.

How do I safely replace hyperlink text in Word? One-sentence conclusion

Replace only the visible text of hyperlinks. Operate on each child Run through the Hyperlink object; do not assign to the paragraph's text property as a whole, otherwise the URL relationship will be lost.

Your situationRecommended PracticesCause
Regular external link, text consists of a single RunFind the Hyperlink using iter_inner_content(), clear it, then write new textKeep the <w:hyperlink> container and r:id relationship, URL unchanged
Hyperlink text contains multiple runs with different formattingFirst clear all child Runs, then write a new RunAvoid replacing only runs[0], which would leave residual text
Table of contents or cross-references pointing to internal document bookmarksKeep fragment, do not modify the targetThese links have an empty address, and forcibly validating or concatenating the URL would cause false positives.
Hyperlinks spanning a page break, or nested within content controls or fieldsMarked for manual reviewFragile structure; python-docx has limited support for complex fields.

Why does clicking the hyperlink fail to navigate after I changed its text?

When handling Word document translation or content cleanup, a frequent failure is this: the script successfully replaces "Click here" with "点击此处" (Chinese for "click here"), but when the user clicks the new text, either nothing happens or it jumps to the wrong page. The root cause is that python-docx's Paragraph.text is readable and writable, but its assignment behavior is destructive. When reading, the library concatenates the visible text of ordinary text and hyperlinks into a single string; when assigning, it effectively overwrites the entire paragraph with a new plain-text Run, and the URL relationship originally encapsulated in <w:hyperlink> is discarded along with it.

In OpenXML, a hyperlink is not a simple text property but a structured container holding multiple Runs. To modify a hyperlink safely, you must bypass paragraph-level text operations and work inside the Hyperlink object, precisely replacing the text of its child Runs while keeping the outer container intact. This is not only a matter of code correctness but also a basic requirement in document translation for avoiding "dead links."

Synthetic Example: Correct Output and Boundary Traps

To illustrate the point, we construct a synthetic scenario that contains no real customer data. Suppose the input document contains this sentence: "Please visit Official Documentation for details."

Expected correct output: After processing, the <w:hyperlink> node in the paragraph XML still exists, and the relationship ID referenced by its r:id remains unchanged, with the corresponding URL still https://example.com/docs. Only the content of <w:t> inside that node changes to "Official Documentation (Chinese) " (Official Documentation (Chinese)). The formatting and content of the rest of the paragraph are unaffected.

Typical Errors and Boundary Inputs:

  1. Direct assignment overwrite: Executingparagraph.text = paragraph.text.replace('官方文档', '官方文档(中文)'). The hyperlink disappears, the entire paragraph becomes plain text, and the URL is permanently lost.
  2. Multi-Run hyperlink: If, in the text "官方文档" (Official Documentation), "官方" (Official) is bold and "文档" (Documentation) is in regular style, Word splits it into two Runs. If the code assumes hyperlink.runs[0] is the entire text and replaces it as a whole, the second Run remains, and the final display becomes "Official Documentation (Chinese) Documentation".
  3. Internal bookmark link: Hyperlinks in a table of contents often have no HTTP address and instead point to an internal _Toc bookmark in the document. In this case address is empty, and the bookmark reference is stored in the fragment attribute. If the code forcibly checks for the http prefix or tries to concatenate a URL, these valid links will be misidentified as abnormal or incorrectly modified.

Code for Safely Replacing Hyperlink Text

This example shows how to update visible text without breaking link structure. This code is for logical demonstration only; please run it in an environment where you have locked your own dependencies. Before use, prepare for yourself an input input.docx containing at least one external hyperlink, for example, manually insert a "官方文档" link pointing to https://example.com/docs in Word.

# 依赖: python-docx 1.2 系列(本次运行环境见 QA 清单) (Hyperlink 对象支持)
# 注意: 本示例不验证网络请求,仅在内存中操作文档结构
from docx import Document
from docx.text.hyperlink import Hyperlink

def translate_hyperlink_text(doc_path, source_text, target_text):
    """
    安全替换超链接可见文本,保留原始URL目标。
    仅当超链接完整文本精确匹配source_text时替换。
    """
    doc = Document(doc_path)
    replaced_count = 0

    for para in doc.paragraphs:
        # 必须使用 iter_inner_content 而非 runs,以捕获超链接对象
        for item in para.iter_inner_content():
            # 显式类型检查,确保是Hyperlink对象
            if isinstance(item, Hyperlink):
                # 精确匹配完整超链接文本,避免部分匹配导致结构损坏
                if item.text == source_text:
                    # 清空所有子Run的文本,防止多Run残留
                    for run in item.runs:
                        run.text = ""
                    # 将译文写入第一个Run,保留其原有格式
                    if item.runs:
                        item.runs[0].text = target_text
                        replaced_count += 1
                    else:
                        # 防御性处理:空超链接容器
                        print(f"警告: 发现无Run的超链接容器,跳过")

    assert replaced_count > 0, "未找到匹配的超链接,请检查源文本"
    return doc

# 使用示例(需读者自备 input.docx):
# new_doc = translate_hyperlink_text("input.docx", "官方文档", "Official Docs")
# new_doc.save("output.docx")

The key to this code is using iter_inner_content() to iterate over paragraph content. It can yield Run and Hyperlink objects in document order, unlike the runs property, which ignores hyperlink containers. The replacement strategy adopts "clear first, then write," ensuring that even if a hyperlink consists of multiple runs with different formatting, no leftover text remains. Assertion statements are used to quickly expose "not found" problems in automated workflows, avoiding silent failures.

📊 Core Comparison

MethodResultMain risks
Assign a value to paragraph.textHyperlinks disappear, and the entire paragraph turns into plain textURL permanently lost
Replace only hyperlink.runs[0]Text may remainMulti-Run hyperlink display error
Clear and rewrite each Run one by one via HyperlinkPreserve hyperlink containers and relationship IDsAdditional acceptance testing is needed for boundary cases such as line breaks, bookmarks, and cross-page content.

Acceptance Criteria and Boundaries of Manual Review

Code demonstrations do not equal end-to-end results. Before delivery, check against the table below, and clearly specify which cases should be handed over to human handling.

Observed PhenomenonHandling DecisionNotes
After replacement, the link correctly jumps to the original URLPassBasic functionality acceptance
Hyperlink text containing line breaks or tab charactersThe code demo only handles plain text; in practice, special character mappings need to be preservedVerify the handling of line breaks and tab characters against the official documentation
Hyperlink pointing to a document-internal bookmark (address is empty)Fragment is preserved, target is not modifiedTables of contents and cross-references belong to this category; the url property returns an empty string
Hyperlinks spanning page breaksMarked for manual reviewStructure is fragile when contains_page_break=True
Same URL corresponding to multiple different visible textsHandle each according to context; bulk replacement is prohibitedTerminology consistency must be judged in light of the glossary
Hyperlinks nested inside content controls or fieldsHand off to manual processingpython-docx has limited support for complex fields

Please note: this solution does not apply to mail merge fields, links inside SmartArt, or protected document regions. In these scenarios the XML structure is highly specialized, and a general-purpose parser may cause irreversible damage. When encountering such files, they should be flagged and excluded during the preprocessing stage.

🎯 Which Approach Suits You?

If you are dealing with ordinary external links

Replace them run by run using Hyperlink objects, and confirm that after the replacement r:id and the URL remain unchanged.

If you are working with a table of contents or cross-references

Keep fragment, do not validate the http prefix, and do not modify bookmark targets.

If your hyperlink text contains multiple formats

First clear all child Runs, then write a new Run, and note that after replacement the style is taken from the first Run.

If the link is located in a page break, content control, field, SmartArt, or protected region

Hand it off to a human directly; do not batch-rewrite it with a generic script.

Self-Contained Hyperlink Sample

The following only constructs OOXML relationships and does not access external URLs. The replacement style is taken from the first Run. If the original link contains multiple styles, a separate segment mapping must be defined. It cannot be considered lossless for all mixed formatting.

from io import BytesIO
from docx.oxml import OxmlElement
from docx.oxml.ns import qn
from docx.opc.constants import RELATIONSHIP_TYPE as RT
source = Document()
p = source.add_paragraph()
link = OxmlElement("w:hyperlink")
rid = p.part.relate_to("https://example.com/", RT.HYPERLINK, is_external=True)
link.set(qn("r:id"), rid)
run = OxmlElement("w:r")
text = OxmlElement("w:t")
text.text = "Docs"
run.append(text)
link.append(run)
p._p.append(link)
stream = BytesIO()
source.save(stream)
stream.seek(0)
changed = translate_hyperlink_text(stream, "Docs", "Documentation")
found = list(changed.paragraphs[0].hyperlinks)
assert found[0].text == "Documentation"
assert found[0].address == "https://example.com/"

References and Next Steps

Using this checklist for document translation

Word translation tends to mix up content issues with formatting issues. Putting style, header, and table checks into the delivery checklist lets reviewers know where to look.

OmniDoc's document translation supports formats such as PDF, Word, PPT, and Excel. Scanned documents have their text recognized first, tables are translated cell by cell with rows and columns preserved, and PDFs produce two versions: a bilingual side-by-side version and a translation-only version. Paid translation also lets you upload a glossary and enable context-aware translation.

❓ Frequently Asked Questions (FAQ)

1. Why can't you directly assign to a paragraph's text to replace hyperlink text?

Because assignment replaces the entire paragraph with a single plain-text run, which discards the hyperlink container and its URL relationship, so the link disappears.

2. What happens when a hyperlink consists of multiple Runs and only the first Run is replaced?

The second and subsequent Runs remain, and the result may display duplicated text such as "官方文档 (中文) 文档" (a repeated-text artifact like this).

3. Why is the URL empty for hyperlinks in the table of contents?

Table of contents links usually point to_Toc bookmarks inside the document, which have no HTTP address. The bookmark reference is stored in the fragment attribute and should be preserved rather than modified.

4. Which hyperlinks should be handled manually?

Hyperlinks that span page breaks, are nested within content controls or fields, or are located in mail merge fields, SmartArt, or protected regions should be handled manually.

📝 Summary

Replacing hyperlink text: the key is to operate on the Run objects inside the Hyperlink object, rather than assigning to the whole paragraph at once, and to check edge cases item by item before delivery. When working with real documents, keep the original file first, then verify with real samples.

Try it now: upload a document and start translating right away, with the original layout preserved.

Updated 2026-11-29