Below is one way to do it using a Python script and BeautifulSoup. This script will:
- Iterate over all files in your
aspx folder.
- For each file, parse its contents.
- Extract the content inside the
<div align=justify> element.
- Write that extracted content to a file with the same name inside a folder called
justify.
Before running the script, make sure you have BeautifulSoup installed. You can install it via pip if you haven’t already:
pip install beautifulsoup4
Here’s the complete Python script:
import os
from bs4 import BeautifulSoup
# Define the input and output directories
input_dir = 'aspx'
output_dir = 'justify'
# Create the output directory if it doesn't exist
if not os.path.exists(output_dir):
os.makedirs(output_dir)
# Process each file in the input directory
for filename in os.listdir(input_dir):
# Check if the file ends with .aspx (you can adjust the filter if needed)
if filename.lower().endswith('.aspx'):
input_path = os.path.join(input_dir, filename)
output_path = os.path.join(output_dir, filename)
# Read the content of the file
with open(input_path, 'r', encoding='utf-8') as file:
content = file.read()
# Parse the HTML content
soup = BeautifulSoup(content, 'html.parser')
# Find the first <div> with attribute align="justify"
div_tag = soup.find('div', align="justify")
if div_tag:
# Get the inner HTML of the div
inner_html = div_tag.decode_contents()
else:
inner_html = '' # Optionally, handle the case where there's no matching div
# Write the extracted content to the new file in the output directory
with open(output_path, 'w', encoding='utf-8') as file:
file.write(inner_html)
print(f"Extracted content from {filename} and saved to {output_path}.")
How the Script Works
-
Folder and File Handling:
- The script assumes your files are in a folder named
aspx in the current working directory.
- It creates an output folder named
justify if it does not exist.
-
Parsing and Extraction:
- For each
.aspx file, it opens and reads the file.
- It uses BeautifulSoup to parse the file as HTML.
- It finds the
<div> that contains the attribute align="justify".
- If found, it extracts the inner HTML (everything inside the
<div>).
-
Saving the Result:
- The extracted content is then written into a new file inside the
justify directory with the same filename.
Running the Script
-
Save the script (for example, as extract_justify.py).
-
Execute it with a Python interpreter:
python extract_justify.py
This will process your aspx files and create corresponding files in the justify folder containing only the content from the <div align=justify>.