Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save aspose-com-gists/1220e548f245c8cd1db3adf399d93f90 to your computer and use it in GitHub Desktop.

Select an option

Save aspose-com-gists/1220e548f245c8cd1db3adf399d93f90 to your computer and use it in GitHub Desktop.
Code examples for common HTML user cases in Python

HTML Manipulation & Styling in Python – Practical Examples

This GitHub Gist repository contains Python code examples referenced in the How-to Articles chapter of the Aspose.HTML for Python via .NET documentation. This Gist contains ready-to-use Python code snippets for everyday HTML processing, styling, and transformation tasks. It's ideal for developers who need quick and practical solutions without having to study extensive documentation.

Why This Collection?

Every web developer faces these questions:

  • "How do I change background colors programmatically?"
  • "Can I disable scripts before converting HTML to PDF?"
  • "What's the easiest way to dynamically style table cells?"

Stop searching. Start coding. Each example is self-contained and ready to use.

Styling & Appearance

Example Description
Background Colors Change background using inline CSS, internal CSS, or style attributes
Text Colors Modify text colors for single elements or all paragraphs at once
Conditional Styling Apply colors dynamically based on data values
Table Styling Alternate row colors, border customization, cell backgrounds
Border Customization Different colors per side, combined styling techniques

Security & Control

Example Description
Disable Scripts Sandbox configuration to prevent script execution during HTML to PDF conversion
Disable Images Block image loading for faster processing or privacy protection

Utilities

Example Description
Unit Conversion Convert pixels to centimeters and other measurement units
DOM Validation Check if HTML body is empty or contains content

About Aspose.HTML for Python via .NET

Aspose.HTML for Python via .NET is a powerful library that enables developers to create, edit, manipulate, and convert HTML documents programmatically using Python. The HTML Document Object Model is integrated with embedded formats and specifications such as CSS, HTML Canvas, SVG, XPath, and JavaScript out-of-the-box, which extend the manipulation functionality and rendering quality.

Prerequisites

  • Python 3.5+
  • .NET Core / .NET 5+ runtime
  • Windows, macOS, or Linux
  • Aspose.HTML for Python via .NET installed from PyPI

How to Use These Examples

  1. Install the Aspose.HTML Python package:
   pip install aspose-html-net
  1. Clone or download this gist to your local machine.
  2. Adjust paths or configuration settings as needed for your environment.
  3. Run your project to see each example in action.

Related Resources

Aspose.HTML for Python via .NET – How-to Articles
# How to style HTML elements with colors using Python
# Learn more: https://docs.aspose.com/html/python-net/how-to-change-background-color/
import aspose.html as ah
# Create an empty HTML document
document = ah.HTMLDocument()
# Access the existing <head> element
head = document.get_elements_by_tag_name("head")[0]
# Create a <style> element and define CSS rules
style = document.create_element("style")
style.inner_html = """
body {
background-color: #f7dba7;
color: #333333;
}
.highlight {
color: #d35400;
font-weight: bold;
}
"""
# Inject the <style> block into the document <head>
head.append_child(style)
# Create a regular paragraph and assign text content
p = document.create_element("p")
p.text_content = "This is a paragraph with default text color."
# Create another paragraph and apply the "highlight" CSS class
highlight = document.create_element("p")
highlight.set_attribute("class", "highlight")
highlight.text_content = "This line uses the .highlight color style."
# Append both paragraphs to the <body> section of the HTML document
document.body.append_child(p)
document.body.append_child(highlight)
# Save the HTML document to a file
document.save("colored-output.html")
# Disable loading images in HTML with sandbox configuration using Python
# Learn more: https://docs.aspose.com/html/python-net/sandboxing/
import os
import aspose.html as ah
import aspose.html.converters as conv
import aspose.html.saving as sav
# Prepare HTML code and save it to a file
code = "<span style=\"background-image:url('https://docs.aspose.com/html/images/work/lioness.jpg')\">Hello, World!!</span> " \
"<script>document.write('Have a nice day!');</script>"
output_dir = "output"
os.makedirs(output_dir, exist_ok=True)
html_path = os.path.join(output_dir, "sandboxing.html")
output_pdf = os.path.join(output_dir, "sandboxing-out.pdf")
with open(html_path, "w", encoding="utf-8") as file:
file.write(code)
# Create an instance of Configuration
with ah.Configuration() as configuration:
# Mark 'IMAGES' as an untrusted resource
configuration.security |= ah.Sandbox.IMAGES
# Initialize an HTML document with the specified configuration
with ah.HTMLDocument(html_path, configuration) as document:
# Convert HTML to PDF
conv.Converter.convert_html(document, sav.PdfSaveOptions(), output_pdf)
# How to disable scripts for HTML to PDF conversion using Python
# Learn more: https://docs.aspose.com/html/python-net/sandboxing/
import os
import aspose.html as ah
import aspose.html.converters as conv
import aspose.html.saving as sav
# Define input and output directories
data_dir = "data"
output_dir = "output"
os.makedirs(output_dir, exist_ok=True)
# Create an instance of the Configuration class
with ah.Configuration() as config:
# Mark "scripts" as an untrusted resource
config.security |= ah.Sandbox.SCRIPTS
# Initialize an HTML document with the specified configuration
html_path = os.path.join(data_dir, "document-with-scripts.html")
with ah.HTMLDocument(html_path, config) as doc:
# Convert HTML to PDF
output_pdf = os.path.join(output_dir, "document-sandbox.pdf")
conv.Converter.convert_html(doc, sav.PdfSaveOptions(), output_pdf)
# Change background color for HTML paragraph using Python
# Learn more: https://docs.aspose.com/html/python-net/how-to-change-background-color/
import os
import aspose.html as ah
# Prepare output path for document saving
output_dir = "output/"
os.makedirs(output_dir, exist_ok=True)
save_path = os.path.join(output_dir, "change-background-color-p-inline-css.html")
# Prepare path to the source HTML file
data_dir = "data/"
document_path = os.path.join(data_dir, "file.html")
# Create an instance of an HTML document
with ah.HTMLDocument(document_path) as doc:
# Find the first paragraph element
paragraph = doc.get_elements_by_tag_name("p")[0]
# Set the style attribute with background-color property
paragraph.set_attribute("style", "background-color: #fff0f5;")
# Save the modified HTML document to a file
doc.save(save_path)
# Change background color for table cells using Python
# Learn more: https://docs.aspose.com/html/python-net/how-to-change-background-color/
import os
import aspose.html as ah
# Prepare directories
data_dir = "data"
output_dir = "output"
os.makedirs(output_dir, exist_ok=True)
# Input and output paths
document_path = os.path.join(data_dir, "table.html")
save_path = os.path.join(output_dir, "change-table-cell-background.html")
# Create an instance of the HTML document
with ah.HTMLDocument(document_path) as doc:
# Select all <td> elements
cells = doc.get_elements_by_tag_name("td")
print("Found cells:", cells.length)
# Loop through each table cell and set alternating background colors
for i in range(cells.length):
cell = cells[i]
color = "#f3d2dd" if i % 2 == 0 else "#ffffff"
cell.set_attribute("style", f"background-color: {color};")
# Save the modified HTML document
doc.save(save_path)
print("Saved to:", save_path)
# Change background color with inline CSS using Python
# Learn more: https://docs.aspose.com/html/python-net/how-to-change-background-color/
import os
import aspose.html as ah
# Define the output path for saving the document
output_dir = "output/"
save_path = os.path.join(output_dir, "change-background-color-inline-css.html")
# Define the path to the source HTML file
data_dir = "data/"
document_path = os.path.join(data_dir, "file.html")
# Create an instance of an HTML document
document = ah.HTMLDocument(document_path)
# Find the <body> element to set a style attribute
body = document.get_elements_by_tag_name("body")[0]
# Set the style attribute with background-color property
current_style = body.get_attribute("style") or ""
new_style = current_style + "background-color: lavenderblush"
body.set_attribute("style", new_style)
# Save the HTML document to a file
document.save(save_path)
# Change background color for HTML using internal CSS using Python
# Learn more: https://docs.aspose.com/html/python-net/how-to-change-background-color/
import os
import aspose.html as ah
# Define paths
output_dir = "output/"
save_path = os.path.join(output_dir, "change-background-color-internal-css.html")
data_dir = "data/"
document_path = os.path.join(data_dir, "file.html")
# Create an instance of an HTML document
document = ah.HTMLDocument(document_path)
# Find the <body> element
body = document.get_elements_by_tag_name("body")[0]
# Remove the background-color property from the style attribute
current_style = body.get_attribute("style") or ""
updated_style = " ".join(prop for prop in current_style.split(";") if not prop.strip().startswith("background-color"))
body.set_attribute("style", updated_style)
# Create a <style> element with CSS rules for the background color
style = document.create_element("style")
style.text_content = "body { background-color: rgb(255 240 245) }"
# Find the <head> element and append the <style> element
head = document.get_elements_by_tag_name("head")[0]
head.append_child(style)
# Save the HTML document to a file
document.save(save_path)
# Change color for four sides of the border using Python
# Learn more: https://docs.aspose.com/html/python-net/how-to-change-border-color/
import os
import aspose.html as ah
# Setup directories and define paths
data_dir = "data"
output_dir = "output"
os.makedirs(output_dir, exist_ok=True)
document_path = os.path.join(data_dir, "file.html")
save_path = os.path.join(output_dir, "change-four-border-color.html")
# Create an instance of an HTML document
with ah.HTMLDocument(document_path) as document:
# Find the first <h1> element
header = document.get_elements_by_tag_name("h1")[0]
# Set inline CSS for border style and different border colors on each side
header.set_attribute("style", "border-style: solid; border-color: red blue green gray;")
# Save the modified HTML document
document.save(save_path)
print("File saved to:", save_path)
# Change border color for HTML using internal CSS in Python
# Learn more: https://docs.aspose.com/html/python-net/how-to-change-border-color/
import os
import aspose.html as ah
# Setup directories and define paths
data_dir = "data"
output_dir = "output"
os.makedirs(output_dir, exist_ok=True)
document_path = os.path.join(data_dir, "file.html")
save_path = os.path.join(output_dir, "change-border-color-internal-css.html")
# Create an instance of an HTML document
with ah.HTMLDocument(document_path) as document:
# Create a <style> element and set CSS for <p> elements
style = document.create_element("style")
style.text_content = "p {border-style: solid; border-color: rgb(220,30,100); }"
# Find the <head> element and append the <style> element
head = document.get_elements_by_tag_name("head")[0]
head.append_child(style)
# Save the modified HTML document
document.save(save_path)
# Change HTML text color using Python
# Learn more: https://docs.aspose.com/html/python-net/how-to-change-text-color/
import os
import aspose.html as ah
# Setup directories and define paths
data_dir = "data"
output_dir = "output"
os.makedirs(output_dir, exist_ok=True)
save_path = os.path.join(output_dir, "change-text-color-inline-css.html")
document_path = os.path.join(data_dir, "file.html")
# Create an instance of an HTML document
with ah.HTMLDocument(document_path) as doc:
# Find the first paragraph element
paragraph = doc.get_elements_by_tag_name("p")[0]
# Set the style attribute with color property
paragraph.set_attribute("style", "color: #8B0000;")
# Save the modified HTML document to a file
doc.save(save_path)
# Change color for all paragraphs in HTML using Python
# Learn more: https://docs.aspose.com/html/python-net/how-to-change-text-color/
import os
import aspose.html as ah
# Prepare an output path for saving the document
output_dir = "output"
os.makedirs(output_dir, exist_ok=True)
save_path = os.path.join(output_dir, "change-text-color-internal-css.html")
# Prepare a path to the source HTML file
data_dir = "data"
document_path = os.path.join(data_dir, "file.html")
# Create an instance of an HTML document
with ah.HTMLDocument(document_path) as doc:
# Create a <style> element and set CSS for the all <p> elements
style = doc.create_element("style")
style.text_content = "p { color: #8B0000 }"
# Find the <head> element and append the <style> element
head = doc.get_elements_by_tag_name("head")[0]
head.append_child(style)
# Save the modified HTML document to a file
doc.save(save_path)
# Change table border color using Python
# Learn more: https://docs.aspose.com/html/python-net/how-to-change-border-color/
import os
import aspose.html as ah
# Prepare an output path for saving the document
output_dir = "output"
os.makedirs(output_dir, exist_ok=True)
save_path = os.path.join(output_dir, "change-table-border-color-inline-css.html")
# Prepare a path to the source HTML file
data_dir = "data"
document_path = os.path.join(data_dir, "table.html")
# Create an instance of an HTML document
with ah.HTMLDocument(document_path) as doc:
# Create a CSS selector to select the first table element
element = doc.query_selector("table")
# Set inline style for the selected element
element.set_attribute("style", "border: 2px #0000ff solid;")
# Save the modified HTML document to a file
doc.save(save_path)
# Change table border color using internal CSS in Python
# Learn more: https://docs.aspose.com/html/python-net/how-to-change-border-color/
import os
import aspose.html as ah
# Prepare directories and input and output paths
output_dir = "output"
os.makedirs(output_dir, exist_ok=True)
data_dir = "data"
document_path = os.path.join(data_dir, "table.html")
save_path = os.path.join(output_dir, "change-table-border-color-internal-css.html")
# Create an instance of an HTML document
with ah.HTMLDocument(document_path) as doc:
# Create a <style> element and set CSS for the <table> element
style = doc.create_element("style")
style.text_content = "table { border-style:solid; border-color:rgb(0, 0, 255) }"
# Find the <head> element and append the <style> element
head = doc.get_elements_by_tag_name("head")[0]
head.append_child(style)
# Save the modified HTML document to a file
doc.save(save_path)
# Change text color based on data in HTML using Python
# Learn more: https://docs.aspose.com/html/python-net/how-to-change-text-color/
import os
import aspose.html as ah
output_dir = "output"
os.makedirs(output_dir, exist_ok=True)
save_path = os.path.join(output_dir, "conditional-text-color.html")
html_content = """
<html>
<body>
<p>Score: 85</p>
<p>Score: 42</p>
<p>Score: 73</p>
</body>
</html>
"""
# Initialize the HTML document
with ah.HTMLDocument(html_content, ".") as doc:
paragraphs = doc.get_elements_by_tag_name("p")
for p in paragraphs:
text = p.text_content
score = int(text.split(":")[1].strip())
# Apply color conditionally
color = "green" if score >= 70 else "red"
p.set_attribute("style", f"color: {color};")
# Save the modified document
doc.save(save_path)
# Convert px to cm using Python
# Learn more: https://docs.aspose.com/html/python-net/
import aspose.html.drawing as dr
# Convert 1000.0 pixels to centimeters
px = dr.Unit.from_pixels(1000.0) # Specify the unit type explicitly
cm = px.get_value(dr.UnitType.CM) # Convert to centimeters
print(cm)
# Сhange border color for <h1> element using Python
# Learn more: https://docs.aspose.com/html/python-net/how-to-change-border-color/
import os
import aspose.html as ah
# Prepare output directory and path for saving
output_dir = "output"
os.makedirs(output_dir, exist_ok=True)
save_path = os.path.join(output_dir, "change-border-color.html")
# Prepare path to source HTML file
data_dir = "data"
document_path = os.path.join(data_dir, "file.html")
# Create an instance of an HTML document
with ah.HTMLDocument(document_path) as document:
# Find the first <h1> element
header = document.get_elements_by_tag_name("h1")[0]
# Set inline CSS properties
header.set_attribute("style", "color: #8B0000; border-style: solid; border-color: rgb(220,30,100);")
# Save the modified HTML document
document.save(save_path)
# Check if HTML body is empty using Python
# Learn more: https://docs.aspose.com/html/python-net/
import aspose.html as ah
# Load the HTML document
with ah.HTMLDocument("document.html") as document:
# Get the body element
body = document.body
# Check if the body element contains any non-empty text content
if body.text_content and not body.text_content.isspace():
print("Non-empty HTML elements found")
else:
print("No child nodes found in the body element.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment