HTML to Plain Text Without Gluing Paragraphs Together

When you use Beautiful Soup to extract web page content, the most common issue isn't extraction failure, but rather that the extracted text gets "stuck" togethe

When you extract web page content with Beautiful Soup, the most common problem is not extraction failure. The text comes out "stuck" together: <p>Hello</p><p>World</p> becomes HelloWorld, or the line breaks between list items disappear. This guide is for developers and document editors who need clean plain text from HTML, and it explains why the default behaviour causes this.

The fix is to control the output with the parameters of get_text() rather than trying to repair line breaks afterwards with regular expressions. You will learn how the separator and strip parameters work together, how to build synthetic test cases that cover typical boundary problems, and how to run a deterministic check on the result.

The examples use synthetic samples. Keep the original copies of any important files, and check your output against the boundaries and acceptance criteria described below.

How do you stop extracted HTML text from sticking together? The short answer

Pass separator='\n' and strip=True to get_text(), and remove script nodes before extraction, because the separator only formats text and does not clean content.

Your situationWhat to doWhy
Paragraphs or list items run togetherCall get_text() with separator='\n'The separator is inserted between text nodes
Output has indentation or dirty spacesAdd strip=TrueEach text fragment is stripped before joining
Output still contains alert(1) or other script textRemove script tags before extractingget_text parameters handle formatting, not content cleansing
Output has extra blank linesFilter out empty lines after the splitPure whitespace nodes remain in the DOM
Structure is lost in tables or dynamic pagesRecord the gap and change your collection strategyStatic parsing is not the same as browser rendering

Why does the default behaviour glue text together?

get_text() accepts two key parameters: separator and strip. If you pass no arguments, it concatenates all text nodes in the tag tree directly. For block-level elements such as div, p and li, this is a serious problem. Line breaks and indentation in the HTML source often become whitespace strings or are ignored during parsing, so the semantic boundaries between blocks are lost.

What does the separator parameter do?

The separator parameter sets what is inserted between text nodes.

  • Setting it to '\n' is the most common approach.
  • It is not perfect. In deeply nested HTML, a global line break can produce many blank lines.

What does the strip parameter do?

The strip parameter controls whether leading and trailing whitespace is removed from each text fragment.

  • With strip=True, Beautiful Soup calls .strip() on each individual NavigableString first, then joins them with the separator.
  • <p> Hello </p> becomes a clean Hello, instead of \n Hello \n with dirty whitespace.

Why do you need both parameters?

  • Separator only: the output keeps meaningless indentation spaces.
  • Strip only: each line is clean, but the lines may still stick together.
  • Both together: each fragment is clean and the fragments are separated.

How do you build test cases for block boundaries?

To validate the extraction logic, build a synthetic HTML sample that contains typical boundary problems. Do not rely on unstable live web pages. The sample below covers three scenarios: block-level element adhesion, inline element spacing and extraneous whitespace.

Input sample (synthetic example):

<div>
    <p>第一段文字</p>
    <p>第二段文字<span>内联补充</span></p>
    <ul>
        <li> 列表项A </li>
        <li>列表项B</li>
    </ul>
</div>

Expected correct output:

第一段文字

第二段文字
内联补充

列表项A
列表项B

Note the following about this output:

  • separator='\n' acts on the extracted text nodes. It does not insert double line breaks based on block-level tags automatically.
  • A clear line break must appear between paragraphs and list items, and extra spaces before or after list items should be removed.
  • "Second paragraph of text" and "inline supplement" sit in different tags and are both text nodes, so the separator places them on separate lines.

What happens with script tags and other error inputs?

Consider the input <p>End</p><script>alert(1)</script><p>Start</p>. If script tags are not filtered, the text-based parser treats script nodes and other node types alike, so the output still contains alert(1) even when a separator is set.

The correct approach is to remove unwanted tags before you extract the text. Use soup.find_all('script') to find and remove them, or skip specific tag types while you traverse the tree with a generator. The get_text parameters only solve formatting problems. They do not clean the content.

How do you run the Python check?

The following code builds the sample above in memory and performs a deterministic check. It requires the beautifulsoup4 library, version 4.9.0 or later is recommended. The code makes no network requests and is fully self-contained.

If you need to test an external file:

  1. Save the HTML as a UTF-8 encoded file.
  2. Open it with open('file.html', encoding='utf-8') to avoid parsing errors caused by encoding problems.
from bs4 import BeautifulSoup

# 合成示例:模拟常见的HTML文本边界问题
html_content = """
<div>
    <p>第一段文字</p>
    <p>第二段文字<span>内联补充</span></p>
    <ul>
        <li> 列表项A </li>
        <li>列表项B</li>
    </ul>
</div>
"""

soup = BeautifulSoup(html_content, 'html.parser')

# 关键配置:separator定义边界,strip清理碎片空白
text_result = soup.get_text(separator='\n', strip=True)

# 过滤空行以获得干净的语义行
lines = [line for line in text_result.split('\n') if line]

# 验收断言:确保边界清晰且无脏数据
assert lines[0] == '第一段文字', f"段落粘连或内容错误: {lines[0]}"
assert lines[1] == '第二段文字', "块级元素间未正确分隔"
assert lines[2] == '内联补充', "内联元素文本节点被错误合并"
assert lines[3] == '列表项A', f"列表项前置空格未清除: '{lines[3]}'"
assert lines[4] == '列表项B', "列表项间边界丢失"

print("提取结果预览:")
for i, line in enumerate(lines):
    print(f"{i}: [{line}]")

The expected output is five lines of clean text.

  • If your environment produces extra blank lines, pure whitespace NavigableString nodes remain in the DOM and were not stripped. This is normal behaviour for html.parser. Filter the empty lines with a list comprehension after the split.
  • Do not run this code directly on complex pages in production. It exists only to demonstrate how the parameters combine.

What are the acceptance criteria and manual review thresholds?

Automated extraction will never reach 100% visual fidelity. The table below shows how to tell repairable problems from problems that need manual intervention. These judgements are based on what the DOM structure shows, not on subjective impressions.

ObservationWhat should be doneWhat not to infer
Inline node separatorCheck whether the sentence has been split into fragmentsThe separator applies to text nodes
Table flatteningPreserve the row and column structure and process tables separatelyYou cannot rely on get_text alone
Dynamically rendered contentRecord the gap explicitlyStatic parsing is not equivalent to browser rendering

This approach does not apply everywhere. If your HTML contains a lot of text generated by CSS pseudo-elements, Canvas-rendered content or Shadow DOM, Beautiful Soup cannot extract meaningful information. In those cases, stop adjusting parameters. Change your data collection strategy or accept the missing information.

How do you apply this checklist to document translation?

Process the body text, links, code and structure of a web document separately. Add the protected sections to your acceptance checklist, then assess the readability and visual presentation of the translated page.

OmniDoc translates PDF, Word, PowerPoint and Excel files: scanned pages are recognized first, table cells are translated one by one so tables keep their rows and columns, and a PDF comes back as both a bilingual and a translation-only file. Paid translation adds a glossary and context translation.

References and next steps

Next, create a synthetic test set with 5 to 10 typical boundary cases in your project and run the assertion script above. If the pass rate is lower than you expect, check whether the DOM needs preprocessing before extraction, such as removing script or style elements or expanding specific tags. For structural problems that parameter changes cannot fix, record the specific HTML fragments as benchmark samples for evaluating specialised document-processing tools.

📊 At a glance

SettingWhat the output looks likeVerdict from this guide
No argumentsText nodes are concatenated directly, so paragraphs and list items stick togetherLoses block boundaries
separator onlyLines are separated, but indentation spaces remainKeeps meaningless spaces
strip onlyEach line is clean, but lines may still stick togetherDoes not separate lines
separator='\n' with strip=TrueClean fragments on separate linesRecommended combination

🎯 Which approach fits you?

If you extract paragraphs and list items from pages

Use separator='\n' together with strip=True, then check the output against a synthetic sample.

If you see script text in the output

Remove script tags before you call get_text(), because the parameters do not clean content.

If your pages depend on CSS pseudo-elements, Canvas or Shadow DOM

Stop tuning parameters. Change your collection strategy or accept the missing information.

❓ FAQ

1. Why does my extracted text come out as HelloWorld?

Calling get_text() with no arguments concatenates text nodes directly, so the boundaries between block elements are lost. Passing separator='\n' puts a line break between the fragments.

2. Why do I still see indentation spaces after using the separator?

The separator alone does not remove whitespace from each fragment. Add strip=True so each fragment is stripped before the join.

3. Why does alert(1) still appear in my output?

The get_text parameters only handle formatting. Remove script tags with soup.find_all('script') or skip them while traversing the tree.

4. Why do I get extra blank lines?

Pure whitespace NavigableString nodes remain in the DOM when they are not stripped. Filter the empty lines with a list comprehension after the split.

📝 Summary

Use separator='\n' with strip=True to keep paragraphs and list items apart, and remove script content before extraction. Test your approach with synthetic samples and check each result against the acceptance criteria before you rely on it.

Try it now: upload a document and get it translated with the layout intact

Updated 2026-11-29