Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save aspose-com-gists/1220e548f245c8cd1db3adf399d93f90 to your computer and use it in GitHub Desktop.
Save aspose-com-gists/1220e548f245c8cd1db3adf399d93f90 to your computer and use it in GitHub Desktop.
Code examples for common HTML user cases in Python
Aspose.HTML for Python via .NET – How-to Articles
# Disable loading images in HTML with sandbox configuration using Python
# Learn more: https://docs.aspose.com/html/python-net/
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/
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/
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/
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/
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/
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/
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/
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/
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/
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/
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/
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/
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/
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