To ensure the extracted text from .aspx files looks closer to how it appears on the webpage, we need to handle newlines and spacing more carefully. This involves:
Preserving Block-Level Structure: Block-level elements like <p>, <div>, <h1>, etc., should have their own lines.
Handling Inline Elements: Inline elements (e.g., <span>, <a>) should stay on the same line unless separated by block-level elements.
Removing Excessive Whitespace: Avoid collapsing multiple spaces or newlines into one unless necessary.
Here’s an updated Python script that improves newline handling and produces cleaner, more readable output:
python
import os
from bs4 import BeautifulSoup, Tag
# Define folder paths
input_folder = "justify"
output_folder = "clean"
# Create the output folder if it doesn't exist.
if not os.path.exists(output_folder):
os.makedirs(output_folder)
def clean_html_to_text(soup):
"""
Recursively extract text from BeautifulSoup objects while preserving structure.
"""
output = []
for element in soup:
# Handle strings (text nodes)
if isinstance(element, str):
stripped_text = element.strip()
if stripped_text:
output.append(stripped_text)
# Handle tags (elements)
elif isinstance(element, Tag):
# Block-level elements get their own line
if element.name in ['p', 'div', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'li', 'br']:
output.append(clean_html_to_text(element))
output.append("\n") # Add a newline after block-level elements
# Inline elements stay on the same line
elif element.name in ['span', 'a', 'b', 'i', 'strong', 'em']:
output.append(clean_html_to_text(element))
# Handle lists specially
elif element.name == 'ul' or element.name == 'ol':
list_items = [f"- {clean_html_to_text(li).strip()}" for li in element.find_all('li')]
output.append("\n".join(list_items))
output.append("\n")
# Handle other tags generically
else:
output.append(clean_html_to_text(element))
return " ".join(output).strip()
# Loop over every file in the input folder.
for filename in os.listdir(input_folder):
# Process only .aspx files.
if filename.lower().endswith(".aspx"):
input_path = os.path.join(input_folder, filename)
with open(input_path, "r", encoding="utf-8") as file:
html_content = file.read()
# Use BeautifulSoup to parse the HTML content.
soup = BeautifulSoup(html_content, "html.parser")
# Extract plain text with better formatting.
text_content = clean_html_to_text(soup).strip()
# Define the output .txt filename.
base_name = os.path.splitext(filename)[0]
output_filename = base_name + ".txt"
output_path = os.path.join(output_folder, output_filename)
# Write the cleaned text to the new file.
with open(output_path, "w", encoding="utf-8") as out_file:
out_file.write(text_content)
print(f"Converted '{filename}' to '{output_filename}'.")
Key Improvements in the Script
Recursive Text Extraction:
The clean_html_to_text function recursively processes each element in the HTML tree.
It distinguishes between block-level elements (like <p>, <div>, <h1>) and inline elements (like <span>, <a>).
Block-Level Handling:
Block-level elements are treated as separate lines. For example, paragraphs (<p>) and headings (<h1>, <h2>) are followed by a newline.
List Handling:
Lists (<ul> and <ol>) are converted into bullet points (-) or numbered items, maintaining readability.
Whitespace Management:
Excessive whitespace is trimmed, but meaningful spacing (e.g., between paragraphs) is preserved.
Inline Elements:
Inline elements like <span> and <a> are kept on the same line unless separated by block-level elements.
Example Input and Output
Input HTML (example.aspx):
html
<!DOCTYPE html>
<html>
<head><title>Test Page</title></head>
<body>
<h1>Welcome to the Test Page</h1>
<p>This is a paragraph of text. <a href="#">Click here</a> to learn more.</p>
<ul>
<li>First item</li>
<li>Second item</li>
</ul>
<div>
<p>Another paragraph with <strong>bold text</strong>.</p>
</div>
</body>
</html>
Output Text (example.txt):
code
Welcome to the Test Page
This is a paragraph of text. Click here to learn more.
- First item
- Second item
Another paragraph with bold text.
How to Run the Script
Place the .aspx files in the justify folder.
Run the script in the directory containing the justify folder.
The cleaned .txt files will be saved in the clean folder.
This approach ensures the extracted text closely resembles the layout of the original webpage.