Certainly! Below is a Python script that traverses through a specified folder, identifies XHTML files, and converts their content to Markdown format. The script uses the BeautifulSoup library to parse XHTML content and the html2markdown library to handle the conversion. If you don't have these libraries installed, you can install them using pip.
Step 1: Install Required Libraries
Before running the script, ensure you have the necessary libraries installed. You can install them using pip:
pip install beautifulsoup4 html2markdown
Step 2: Python Script
import os
import sys
from bs4 import BeautifulSoup
import html2markdown
def convert_xhtml_to_markdown(xhtml_content):
"""
Converts XHTML content to Markdown format.
Args:
xhtml_content (str): The XHTML content as a string.
Returns:
str: The converted Markdown content.
"""
# Parse the XHTML content using BeautifulSoup
soup = BeautifulSoup(xhtml_content, 'xml') # Use 'xml' parser for XHTML
# Optionally, prettify the soup object (commented out)
# print(soup.prettify())
# Convert the BeautifulSoup object back to a string
clean_html = soup.get_text(separator='\n')
# Use html2markdown to convert HTML to Markdown
markdown = html2markdown.convert(clean_html)
return markdown
def process_folder(folder_path, output_folder):
"""
Processes all XHTML files in the given folder and converts them to Markdown.
Args:
folder_path (str): Path to the folder containing XHTML files.
output_folder (str): Path to the folder where Markdown files will be saved.
"""
if not os.path.isdir(folder_path):
print(f"Error: The folder '{folder_path}' does not exist.")
sys.exit(1)
# Create output folder if it doesn't exist
os.makedirs(output_folder, exist_ok=True)
# Iterate through all files in the folder
for filename in os.listdir(folder_path):
if filename.lower().endswith(('.xhtml', '.xml', '.html', '.htm')):
xhtml_path = os.path.join(folder_path, filename)
try:
with open(xhtml_path, 'r', encoding='utf-8') as file:
xhtml_content = file.read()
# Convert XHTML to Markdown
markdown_content = convert_xhtml_to_markdown(xhtml_content)
# Define the output Markdown file path
base_name = os.path.splitext(filename)[0]
markdown_filename = base_name + '.md'
markdown_path = os.path.join(output_folder, markdown_filename)
# Write the Markdown content to the file
with open(markdown_path, 'w', encoding='utf-8') as md_file:
md_file.write(markdown_content)
print(f"Converted '{filename}' to '{markdown_filename}'.")
except Exception as e:
print(f"Failed to convert '{filename}': {e}")
def main():
"""
Main function to execute the script.
"""
if len(sys.argv) != 3:
print("Usage: python convert_xhtml_to_md.py <input_folder> <output_folder>")
sys.exit(1)
input_folder = sys.argv[1]
output_folder = sys.argv[2]
process_folder(input_folder, output_folder)
if __name__ == "__main__":
main()
Step 3: Usage Instructions
-
Save the Script:
Save the above script to a file named convert_xhtml_to_md.py.
-
Prepare Folders:
- Input Folder: Ensure you have a folder containing your XHTML files. For example,
input_xhtml.
- Output Folder: Decide on a folder where you want the converted Markdown files to be saved. For example,
output_md.
-
Run the Script:
Open your terminal or command prompt and navigate to the directory containing the convert_xhtml_to_md.py script. Then execute the script with the input and output folder paths as arguments.
python convert_xhtml_to_md.py input_xhtml output_md
Replace input_xhtml with the path to your XHTML files folder and output_md with the desired output folder path.
-
Check the Output:
After running the script, the output_md folder will contain the converted Markdown files corresponding to each XHTML file in the input_xhtml folder.
Notes and Considerations
-
Encoding: The script assumes that the XHTML files are encoded in UTF-8. If your files use a different encoding, you may need to adjust the encoding parameter in the open function accordingly.
-
File Extensions: The script processes files with extensions .xhtml, .xml, .html, and .htm. You can modify the list of extensions in the if statement within the process_folder function if needed.
-
Error Handling: The script includes basic error handling to notify you if a file fails to convert. You can enhance this by adding more specific exception handling based on your requirements.
-
Enhancements:
- Selective Conversion: If you want to convert only specific XHTML files, you can modify the script to include selection criteria.
- Custom Markdown Formatting: The
html2markdown library provides options to customize the Markdown output. Refer to its documentation for more advanced usage.
-
Dependencies Alternative: If you prefer not to use html2markdown, you can use other libraries like markdownify or implement a custom conversion using BeautifulSoup. However, using existing libraries simplifies the process and ensures better handling of various HTML/XHTML elements.
Example XHTML to Markdown Conversion
Consider the following sample XHTML content:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Sample XHTML</title>
</head>
<body>
<h1>Welcome to XHTML to Markdown Converter</h1>
<p>This is a <strong>sample</strong> paragraph with <a href="https://example.com">a link</a>.</p>
<ul>
<li>First item</li>
<li>Second item</li>
</ul>
</body>
</html>
After conversion, the resulting Markdown (Sample.xhtml to Sample.md) would look like:
# Welcome to XHTML to Markdown Converter
This is a **sample** paragraph with [a link](https://example.com).
- First item
- Second item
This demonstrates how headings, bold text, links, and lists are appropriately converted from XHTML to Markdown.
Feel free to customize and enhance the script based on your specific needs!